Classes and Objects in C# with examples
Classes and Objects in C#
A class defines the state and behavior of the basic program components known as objects. Classes create objects and objects use methods to communicate between them. Classes provide a convenient approach for packing together a group of logically related data items and functions that work on them.
In C#, the data items are called fields and the functions are called methods. Calling a specific method in an object is described as sending the object a message.
Defining a Class
A class is a user-defined data type with a template that serves to define its properties. Once the class type has been defined, we can create the ‘variables’ of that type using declarations. In C#, these variables are termed as instances of classes that are the actual objects. It has the following syntax:
class class-name { [variables declaration;] [methods declaration;] }
where the class is a keyword and class-name is any valid of C# identifier.
Objects
In C#, an object is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object.
In C#, objects are created using the new operator. The new operator creates an object of the specified class and it returns a reference to that object.
Example:
Rectangle rect; // declare rect= new Rectangle(); // instantiate
Where the first statement declares a variable to hold the object reference and the second one assigns the object reference to the variable.
Note: It is important to understand that each object has a copy of the instance variables of its class. It means that any changes to the variables of one object will not affect the variables of another.