Some more about references and objects
A reference is just a pointer or handle to the object in memory. It is possible to create an object without giving its handle to any reference:
The above line is a valid statement. It will create an object of Student class without any reference pointing to it. An object is actually eligible to be garbage collected when there is no reference to point it. So, in the above case, the new Student object will instantly be eligible to be garbage collected after its creation. Experienced programmers often call methods on these unreferenced objects like
In the above line, a new object of class Student is created and the CalculatePercentage() method is called on it. This newly created, unreferenced object will be eligible to be garbage collected just after the method CalculatePercentage() completes its execution. I personally won't encourage you to write such statement. The above line is similar to
We assigned null to theStudent so the object above will be destroyed after method call terminates as in the case of previous example. When you write:
a new object of type Student is created at the heap and its handle is given to the reference student1. Let us make another object and give its handle to the reference student2.
Now, If we write
The new reference student3 will also start pointing the student (Nitin Sir) already pointed by student2. Hence both student2 and student3 will be pointing to same student and both can make changes to same object.
Now, If we write
it will also start pointing to the second object (Nitin Sir), leaving the first student (Sachin Chaudhary) unreferenced. It means the first student is now eligible to be garbage collected and can be removed from memory anytime.
If you want a reference to reference nothing, you can set it to null, which is a keyword in C#.