- Learn C# in 7 days
- Gaurav Aroraa
- 449字
- 2021-07-08 09:51:25
Reference type
The actual data is not stored in the variable but it contains reference to variables. In simple words, we can say that the reference type refers to a memory location. Also, multiple variables can refer to one memory location, and if any of these variables change the data to that location, all the variables would get the new values. Here are the built-in reference types:
- class type: A data structure that contains members, methods, properties, and so on. This is also called the object type as this inherits the universal classSystem.Object. In C# 7.0, class type supports single inheritance; we will discuss this in more detail on day seven.
There is a concept called boxing and unboxing that happens once we deal with an object type. In general, whenever value type is converted into the object type, it is called boxing, and when object type is converted into a value type, it is called unboxing.
Take a look at the following code snippet:
private static void BoxingUnboxingExample()
{
int thisIsvalueTypeVariable = 786;
object thisIsObjectTypeVariable = thisIsvalueTypeVariable; //Boxing
thisIsvalueTypeVariable += 1;
WriteLine("Boxing");
WriteLine($"Before boxing: Value of {nameof(thisIsvalueTypeVariable)}: {thisIsvalueTypeVariable}");
WriteLine($"After boxing: Value of {nameof(thisIsObjectTypeVariable)}: {thisIsObjectTypeVariable}");
thisIsObjectTypeVariable = 1900;
thisIsvalueTypeVariable = (int) thisIsObjectTypeVariable; //Unboxing
WriteLine("Unboxing");
WriteLine($"Before Unboxing: Value of {nameof(thisIsObjectTypeVariable)}: {thisIsObjectTypeVariable}");
WriteLine($"After Unboxing: Value of {nameof(thisIsvalueTypeVariable)}: {thisIsvalueTypeVariable}");
}
In the preceding code snippet, we defined boxing and unboxing, where boxing happened when a value type thisIsvalueTypeVariable variable is assigned to an object thisIsObjectTypeVariable. On the other hand, unboxing happened when we cast object variable thisIsObjectTypeVariable to our value type thisIsvalueTypeVariable variable with int. This is the output of the code:

Here, we are going to discuss three important types, which are interface, string, and delegate type:
- interface type: This type is basically a contract that is meant to be implemented by whoever is going to use it. A class or struct may use one or more interface types. One interface type may be inherited from multiple other interface types. We will discuss this in more details on day seven.
- delegate type: This is a type that represents a reference to a method of a parameter list. Famously, delegates are known as function pointers (as defined in C++). Delegates are type- safe. We will discuss this in detail on day four.
- string type: This is an alias of System.String. This type allows you to assign any string value to variables. We will discuss this in detail in the upcoming sections.