Reference types vs value types
Reference types are allocated on the heap and garbage-collected, whereas value types are allocated on the stack so their (de)allocation are generally cheaper.
Arrays of reference types contain just references to instances of the reference type residing on the heap. Value type arrays hold the actual instance of the value type. Value type arrays are much cheaper than reference type arrays.
Value types get boxed when cast to a reference type or one of the interfaces they implement. They get unboxed when cast back to the value type. Boxes are objects that are allocated on the heap and are garbage-collected. Too much boxing and unboxing can have a negative impact.
In contrast, no such boxing occurs for reference types.
Reference type assignments copy the reference, whereas value type assignments copy the entire value. Assignments of large reference types are cheaper than assignments of large value types.
Reference types are passed by reference, whereas value types are passed by value. Changes to an instance of a reference type affect all references pointing to the instance. Value type instances are copied when they’re passed. When an instance of a value type is changed, it doesn’t affect any of its copies.
You can’t have a null value type. “null” only means a memory address reference is missing.
Class
Class is a reference type. When you compare reference types, this comparison checks if the compared objects are the same object (heap location).
You can specify access modifier if required (private, public, protected, internal).
class declaration
class Person
{
public string Name {get; set;}
public int Age {get; set;}
}
create an object
Person person = new Person();
person.Age = 30;
person.Name = "Mario";
Console.WriteLine(person.Name + " " + person.Age); // Mario 30
create another object using the first object we created
Person person2 = person;
person2.Age = 29;
Console.WriteLine(person.Name + " " + person.Age); // Mario 29
Console.WriteLine(person2.Name + " " + person2.Age); // Mario 29
Read More