Class and object C# example-Learn how to create a class and object in C# programs with example. Also, know how and where objects and its references are stored in memory i.e. stack and heap and its de – allocation.
Consider a class is Car and it contains one method run().
To create an object of Car class, we will use new keyword. For example, here we have created one object of Car called Maruti.
Car Maruti = new Car();
/*
* Class and object C# example
*/
//user defined class
class Car {
void run() {
System.out.println("Car is running...");
}
}
// Test
public class Sample {
public static void main(String[] args) {
// Create a reference variable of class type Car
// and create an object of Car using new keyword
Car maruti = new Car();
// Call car function using object maruti with dot operator
maruti.run();
}
}
Car Maruti; => reference is created on stack.
new Car(); => Create object of Car on Heap and address of it is assigned to Maruti reference.
Similarly, we can create multiple objects of class Car. for example,
Car Honda = new Car();
Car ford = new Car();
In the above C#-class and object example program, when Maruti reference goes out of scope, meaning, when main() method ends, reference Maruti will be cleaned from stack and the object resides on Heap will be eligible for garbage collection.
Meaning CLR(common Language Runtime)will clean the object and we don’t have to de- allocate it manually / explicitly like we do in in C++