CHAPTER 3: Introduction to Classes and Objects in C#

Concept of a Class

A class is simply an abstract model used to define a new data types. A class may contain any combination of encapsulated data (fields or member variables), operations that can be performed on data (methods) and accessors to data (properties). For example, there is a class String in the Systemnamespace of .Net Framework Class Library (FCL). This contains an array of characters (data) and provide different operations (methods) that can be applied to its data like ToLowerCase(), Trime(),Substring(), etc. It also has some properties like Length (used to find the length of the string).

A class in C# is declared using the keyword class and its members are enclosed in parenthesis

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376307052417/home/3-classes-and-objects/710.bmp

where MyClass is the name of class or new data type that we are defining here.

Objects

As mentioned above, a class is an abstract model. An object is the concrete realization or instance builton the model specified by the class. An object is created in the memory using the keyword 'new' and isreferenced by an identifier called a "reference".

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376644447719/home/3-classes-and-objects/15.bmp

In the line above, we made an object of type MyClass which is referenced by an identifiermyObjectReference.

The difference between classes and implicit data types is that objects are reference types (passed byreference) while implicit data types are value type (passed by making a copy). Also, objects are created at the heap while implicit data types are stored on stack.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376644224951/home/3-classes-and-objects/14.bmp

Fields

fields are the data contained in the class. Fields may be implicit data types, objects of some other class, enumerations, structs or delegates. In the example below, we define a class named Student containing a student's name, age marks in maths, mark in English, marks in science, total marks, obtained marks and a percentage.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376645653049/home/3-classes-and-objects/16.bmp

you can also initialize the fields with the initial values as we did in totalmarks in the example above. If you don't initialized with their default values. Default values for different data types are shown below.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377168406485/home/3-classes-and-objects/17.bmp

Methods

Methods are the operations performed on the data, A method may take some input values through its parameters and may return a value of a particular data type. The signature of the method takes the form

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376648987889/home/3-classes-and-objects/19.bmp

For example,

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377168406485/home/3-classes-and-objects/17.bmp

Here, we defined a method name FindSum which takes two parameters of int type (num1 and num2) and returns a value of type int using the keyword return. if a method does not return anything, itsreturn type would be void. A method can also optionally take no parameter (a parameterless method)

Class and Objects

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377169263138/home/3-classes-and-objects/class-and-objects/8.bmp

Access Modifiers or Accessibility Levels

In our Student class, everyone has access to each of the fields and methods. So if one wants, he/shecan change the totalMarks from 300 to say 200, resulting in the percentages getting beyond100%, which in most cases we like to restrict. C# provides access modifiers or accessibility levels just for this purpose, i.e.,restricting access to a particular member. There are 5 access modifiers that can be applied to any member of the class. We are listing these along with short description in the order ofdecreasing restriction

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377256490937/home/3-classes-and-objects/class-and-objects/class-and-objects/41.bmp

In Object Oriented Programming (OOP) it is always advised and recommended to mark all your fields asprivate and allow the user of your class to access only certain methods by making them public. For example, we may change our student class by marking all the fields private and the three methods in the class public.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377257469447/home/3-classes-and-objects/class-and-objects/class-and-objects/42.bmp

If you don't mark any member of class with an access modifier, it will be treated as a private member;

this means the default access modifier for the members of a class is private.

You can also apply access modifiers to other types in C# such as the class, interface, struct, enum,delegate and event. For top-level types (types not bound by any other type except namespace) likeclass, interface, struct and enum you can only use public and internal access modifiers with the same meaning as described above. In fact other access modifiers don't make sense to these types. Finally you can not apply access modifiers to namespace.

Properties

You must be wondering if we declare all the fields in our class as private, how can we assign values to them through their reference as we did in the Student class before? The answer is through Properties. C#is the first language to provided the support of defining properties in the language core.

In traditional languages like Java and C++, for accessing the private fields of a class, public methodscalled getters (to retrieve the value) and setters (to assign the value) were defined like if we have aprivate field name

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377259209571/home/3-classes-and-objects/class-and-objects/class-and-objects/13.bmp

then, the getters and setters would be like

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377259486096/home/3-classes-and-objects/class-and-objects/class-and-objects/17.bmp

Using these we could restrict the access to a particular member. For example we can opt to only define the getter for the totalMarks field to make it read only.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377320083155/home/3-classes-and-objects/class-and-objects/class-and-objects/10.bmp

Hence outside the class, one can only read the value of totalMarks and can not modify it. You can alsodecide to check some condition before assigning a value to your field

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377320614791/home/3-classes-and-objects/class-and-objects/class-and-objects/11.bmp

This procedure gives you a lot of control over how fields of your classes should be accessed and dealt in a program. But, the problem is this you need to define two methods and have to prefix the name of your fields with Get or Set. C# provides the build in support for these getters and setters in the form ofproperties. Properties are context sensitive constructs used to read, write or compute private fields ofclass and to achieve control over how the fields can be accessed.

Using Properties

The general Syntax for Properties is

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377324440129/home/3-classes-and-objects/class-and-objects/class-and-objects/10..bmp

Didn't understand it? No problem. Let's clarify it with an example: we have a private field name

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377324729704/home/3-classes-and-objects/class-and-objects/class-and-objects/1w.bmp

We decide to define a property for this providing both getters and setter. We will simply write

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377325045463/home/3-classes-and-objects/class-and-objects/class-and-objects/2e.bmp

We defined a property called 'Name' and provided both a getter and a setter in the form of get { } andset { } blocks. Note that we called our property 'Name' which is accessing the private field 'name'. It is becoming convention to name the property the same as the corresponding field but with first letter inuppercase (for name->Name, for percentage->Percentage). As properties are accessors to certainfields,they are mostly marked as public while the corresponding field is (and should be) mostly private.Finally note in the set { } block, we wrote

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377336874383/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/98.bmp

Here, value is a keyword and contains the value passed when a property is called. In our program we will our property as

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377502073501/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/as2.bmp

While defining properties, we said properties are context sensitive. When we write

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377506325616/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/12.bmp

The compiler sees that the property Name is on the left hand side of assignment operator, so it will call the set { } block of the properties passing "Sachin Chaudhary" as value (which is a keyword). In thenext line when we write

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377506649296/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/j.bmp

the compiler now sees that the property Name is on the right hand side of the assignment operator, hence it will call the get { } block of property Name which will return the contents of the private fieldname ("Sachin Chaudhary" in this case, as we assigned in line 2) which will be stored in the local string variable name. Hence, when compiler finds the use of a property, it checks in which context it iscalled and takes appropriate action with respect to the context.

The last line

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377506820311/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/dg.bmp

Will generate a compile time error (if called outside the Student class) as the name field is declaredprivate in the declaration of class.

You can give the definition of either of get { } or set { } block. If you miss one of these, and user tries to call it, he/she will get compile time error. For example the Length property in String class is readonly; that is, the implementers have only given the definition of get { } block. You can write statements in the get { }, set { } blocks as you do in methods.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377507568417/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/10.bmp

Precautions when using properties

  • Properties don't have argument lists; set, get and value are keywords in C#
  • The data type of value is the same as the type of property you declared when declaring theproperty
  • ALWAYS use proper curly brackets { } and proper indentation while using properties.
  • DON"T try to while the set { } or get { } block in a single line
  • UNLESS your property only assigns and retrieve values from the private fields like

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377515759161/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/dert.bmp

Each object has a reference this which points to itself. Suppose in some method call, our object needs to pass itself, what would we do? Suppose in our class Student, we have a method Store() that stores the information of Student on the disk. In this method, we called another method Save() of FileSystem class which takes the object to store as its parameter.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377511748947/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/18.bmp

We passed this as a parameter to the method Save() which points to the object itself.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377512704560/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/e4.bmp

Here, when Store() is called, the reference theStudent will be passed as a parameter to the Save() method in Store(). Conventionally, the parameters to constructors and other methods are named the same as the name of the fields they refer to and are distinguished only by using this reference.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377513438950/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/2f.bmp

Here in the constructor when we use name or age, we actually get the variables passed in the methodwhich overshadow the instance members (fields) with same name. Hence, to use our fields, we had to use this to distinguish our instance members (fields) with the members passed through the parameters.

This is an extremely useful, widely and commonly used construct. I recommend you practice with "this" for some time until you feel comfortable with it.

Static Members of the class

All the members of the classes that we have seen up till now are instance members, meaning they belong to the object being created. For example, if you have an instance fields name in your Person class then each object of our Person class will have a separate field name of its own. There is anotherclass of members which are called static. Static members belong to the whole class rather then toindividual object. For example, if you have a static phoneNumber field in your Student class, then there will be the single instance of this field and all the objects of this class will share this single field. Changes made by one object to phoneNumber will be realized by the other object. Static members are defined using keyword static

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377517818512/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/ed.bmp

Static members are accessed with the name of class rather than reference to objects. Let's make ourTest class containing main method

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377597712611/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/8.bmp

Here you can see that the phoneNumber is accessed without any reference to the object but with thename of the class it belongs. Static methods are very useful while programming. In fact, the writeLine()and ReadLine() methods that we are using from the start are static methods of Console class. That is the reason why we used to call them with reference to their class rather than making an object of theConsole class. I hope now you are able to understand the syntax of the main method in C# in full. It is declared static as CLR calls it without making any instance of our class. Static variables are useful when you want to cache data that should be available to all objects of the class. You can use static fields,methods, properties and even constructors which will be called before any instance of the class is created. Static constructor are declared like

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377598126281/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/9.bmp

As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non- static context . The reason for being able to call static members from non-static context is that static members belong to the class and are percent irrespective of the existence of even a single object. The definition ofMyMethod() in following code will not compile

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377599026797/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/252.bmp

Some precautionary points in the end

  • Don't put too many static methods in your class as it is against the object oriented design principles and makes your class less extensible.
  • Don't try to make a class with only the static methods and properties unless you have very good reason for doing this.
  • You tend to loose a number of object oriented advantages while using static methods, as static methods can't be overridden which means it can not be used polymorphically, something widely used in the Object Oriented Paradigm of programming.

Some More about MethodsWe mentioned earlier that there are two kinds of 'type' in C#: Value types and Reference types. Valuetypes, such as implicit data types, are passed to methods by value. Reference types, like objects andarrays, are passed by reference.Constructorsconstructors are a special kind of method. A constructor has the following properties:

  • It has the same name as its containing class
  • It has no return type
  • It is automatically called when a new instance or object of a class is created, hence why it's called a constructor.
  • The Constructor contains initialization code for each object, like assigning default values to thefields.

Let us see some example

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377601966871/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/1e.bmp

In this Person class above, we have a private field name, a public constructor which initializes the namefield with string "Sachin Chaudhary" and prints that it has been called, then we have a public property toread/write the private field name. Lets make another class Test which contains the Main() method and which uses the Person class

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377602949955/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/3r.bmp

In our Test class, we made an object of the Person class and printed the name of person. We then changed the value of Name and printed the Name again. The result of the program is:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377603289076/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/4r.bmp

Note that the constructor is called just as we created a new instance of Person class and initialized the field name with string "Sachin Chaudhary" In fact, when we created a new object, we actually call theconstructor of the class

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377758666990/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/63.bmp

That is way constructor is usually made public. If you make your constructor private, no one would be able to make an object of your class outside of it (though a method in the class of course could). That is, if the Person class is defined as:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650791/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/9.bmp

then it would cause as error to write:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650791/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/jo.bmp

The constructors shown so far have been parameter-less, i.e. they do not take any parameters. We can define constructors which take some parameters.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650790/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/3..bmp

Now, the object of class Person can only be created by passing a string into the constructor.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650792/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/se.bmp

If you don't define any constructor for your class, the compiler will generate an empty parameter-lessconstructor for you. That is why we were able to make our Student object even we did not specify anyconstructor for the Student class.

Finalize() Method of Object class

Each class in C# is automatically (implicitly) inherited from the Object class which contains a methodFinalize(). This method is guaranteed to be called when your object is garbage collected (removedfrom memory). You can override this method and put here code for freeing resources that you reserved when using the object. For example,

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650791/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/3f.bmp

Author's Note: I am not going to explain this code for now. if it looks alien to you, read it again when we would have covered inheritance, polymorphism and exceptions. We will explain Garbage Collection in coming issues.

Destructors

Destructors are just the opposite of constructors. These are methods with following properties. It has the same name as the containing class but prefixes it with the ~ (tilde) sign. It is called automatically when the object is about to be destructed (when garbage collector is about to destroy your object). It has no return type. We declare the destructor as

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650791/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/93.bmp

As a matter of fact, the C# compiler internally converts the destructor to the Finalize() method, we just saw above. Destructors are note used very much in common C# programming practice (that is whyJava dropped the idea of destructors). In the days of C++, Programmers had to manage memoryallocation and de-allocation. Destructors were used there to free the memory allocated by the object dynamically. Hence, you probably won't encounter destructors or Finalize() methods that often.

Method and Constructor Overloading

It is possible to have more than one method with the same name and return type but with a differentnumber and type of arguments (parameters). This is called method overloading. For example it is perfectly legal to write:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650789/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/1.bmp

In the checker class above we defined three methods with the name isDefaultValue(). The return typeof all these is bool but all differ from each other in parameterlist. The first two differ in the data typeof the parameters while the third one differ in the number of parameters. When isDefaultValue() is called, the compiler will decide (on the basis of the types and number of parameters being passed) which one of these three to actually call. For example, in our Main() method:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650790/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/2.bmp

Remember the methods are overloaded depending on the parameter list and not on the return type. TheWriteLine() method of Console class in the System namespace has 19 different overloaded forms! See the .Net Framework Documentation or MSDN for all of these.

Overloading Constructors

Since constructors are a special type of method, we can overload constructors similarly.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377770650790/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/3.bmp

Now, if we create an object like

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377773804860/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/w3.bmp

the first constructor will be called initializing name with "Sachin Chaudhary". If we create an objectlike

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377773955621/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/5y.bmp

the second constructor will be called initializing name with "Sachin Chaudhary". As you can see,overloading methods and constructors gives your program a lot of flexibility and reduces a lot ofcomplexity that would otherwise be produced if we had to use different name for these methods (Just consider what would happen to implementers of WriteLine(), who would have had to come up with 19names!)

Value types (out & ref Keywords)

When we pass a variable of an implicit data type to a method, conceptually the runtime generates acopy and passes that copy t the method. It is actually a copy of the variable that is available inside themethod, Hence if you modify a value type variable (passed as a parameter) in a method, the actualvalue of the variable would not be changed outside the method. Let us have in our test class a Main() method and a DoWork() method:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377849529694/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/x.bmp

The program will result in

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377851144195/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/9.bmp

Because a copy of the variable a is passed to the DoWork() method and not the variable a. Also, note that i is the local variable in DoWork() and a is local variable in Main(). Hence, they can be accessed within their containing methods only. In fact, we may define int a; in different methods and each will have its own variable a and none would have correspondence with any other implicitly.

C# provides a keyword, ref, which means that the value type will be passed by reference instead of the of the default by value behavior. Hence, changes done inside the method would reflected back after the method has been called and terminated. Both the method signature and method calling should be declared as ref in order to override the by value characteristic to by ref.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377851460625/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/11.bmp

The program will give the following result:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377851253495/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/10.bmp

In the case of the ref keyword, the variable must be initialized before passing it to the method byreference. C# also provides the out keyword. This is used for passing a variable for output purposes. This will again be passed by reference. However, when using the out keyword, it is not necessary toinitialize the variable.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377852344727/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/5.bmp

The program will give the result

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377851253495/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/10.bmp

Reference types

Objects are implicitly passed by reference. This means that only a copy of the reference is passed to themethods during method invocation. Hence, if we initialize an array (which is an object in C# ) and passit to some method where the array gets change, then this change effect would be visible after themethod has been terminated in the calling method.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377853547018/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/7.bmp

The program will result in

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377853690940/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/8.bmp

Here, we initialized an int type array (nums) with some values. We passed this array to the DoWork() method, which incremented (modified) the contents of the array. Finally, we printed the elements ofarray. As the output suggests, the DoWork() method did change the elements in array (num) and worked on actual array and not on its copy (as is the case in value types).

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 objectwithout giving its handle to any reference:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377943047099/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/9.bmp

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 pointit. 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

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377944018869/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/10.bmp

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

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377944806632/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/11.bmp

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:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377946623068/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/17.bmp

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.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377945506260/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/14.bmp

Now, If we write

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377945688403/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/15.bmp

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 sameobject.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377946427784/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/16.bmp

Now, If we write

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377946744210/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/18.bmp

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 removedfrom memory anytime.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377947877292/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/20.bmp

If you want a reference to reference nothing, you can set it to null, which is a keyword in C#.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1377948090828/home/3-classes-and-objects/class-and-objects/class-and-objects/class-and-objects/class-and-objects/classes-and-objects/class-and-objects/class-and-objects/21.bmp