Class, Record and Struct in C#
Class, Record, and Struct serve as blueprints for creating new objects. Classes Classes are the foundational building blocks of Object-Oriented Programming (OOP). Blueprint and instance // blueprint public class Person { public int ID { get ; set ; } public string Name { get ; set ; } } // instance var p = new Person { ID = 1 , Name = "Mirza" } Inspection Printing the class instance in the console will just display it's name: var p1 = new Person { ID = 1 , Name = "Mirza" }; Console . WriteLine ( p1 ); // Person To print the actual, we'd need print each property explicitly: Console . WriteLine ( p1 . ID ); // 1 Console . WriteLine ( p1 . Name ); // "Mirza" Mutation C# classes are mutable, meaning the originally set values can be altered: var p1 = new Person { ID = 1 , Name = "Mirza" }; Console . WriteLine ( p1 . Name ); // "Mirza" p1 . Name = "Armin" ; Console . WriteLine ( p1 . Name ); // "Armin" That said, this can be tweaked by changing the accessor the class property. public class Person { public int ID { get ; set ; } public string Name { get ; init ; } // <-- } This time around if we try to change the value of the Name property after initialization, the C# compiler will start to complain. var p1 = new Person { ID = 1 , Name = "Mirza" }; p1 . Name = "Edis" ; // ❌ The init accessor allows you to create properties that can only be assigned a value during object initialization. Memory location Classes are reference types and are allocated on the heap. If we create two distinct class objects and assign one to the other, both objects will point to the exact same reference in memory: var p1 = new Person { ID = 1 , Name = "Mirza" }; var p2 = new Person { ID = 2 , Name = "Mirza" }; p1 = p2 ; p1 . Name = "Sead" ; Console . WriteLine ( p1 . Name ); // Sead Console . WriteLine ( p2 . Name ); // Sead If we change a value in one of the objects, it will be reflected in both. Equality Two class instances (objects) aren't equal even if they share the same values: var p1 = new P