Data Types in C# (Reference Data Types).
Notes from this video:
Reference Type: -
reference types are types that store references (addresses) to their data, rather than the data itself.
When we work with reference types, we are dealing with references to objects in memory.
Here are some key points and examples of reference types:
Common Reference Types: -
Classes
Interfaces
Delegates
Arrays
Strings
When we assign a reference type to a variable, we are assigning a reference to the memory location where the object is stored.
Modifying the object through one reference will affect all references to that object.
Reference types are created on the heap.
Example: Class
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
DataTypesExClass obj1 = new DataTypesExClass();//object of DataTypesExClass class
obj1.Name = "John";
obj1.Age = 30;
DataTypesExClass obj2 = obj1; // obj2 references the same object as obj1
obj2.Age = 35;
Console.WriteLine(obj1.Age); // Output: 35
In this example, obj1 and obj2 reference the same DataTypesExClass object. Changing the Age property through obj2 also reflects in obj1.
Example: Array
int[] numbers1 = { 1, 2, 3 };
int[] numbers2 = numbers1; // numbers2 references the same array as numbers1
numbers2[0] = 10;
Console.WriteLine(numbers1[0]); // Output: 10
Here, numbers1 and numbers2 reference the same array. Modifying an element through numbers2 also changes it in numbers1.