Hello Friends,
In today’s article we will learn what is value type and reference type in C#.
In C# the data types are classified based on the how they store the values in memory.
Let’s take the below example in C#
using System;
//Let's declare a new class called Customer
public class Customer
{
public string Name
{
get;
set;
}
}
public class Program
{
public static void Main()
{
int productCode = 104;
Customer newCustomer = new Customer();
newCustomer.Name = "John Doe";
Console.WriteLine("Before->Product Id:{0}", productCode);
//Calling the static method
UpdateValue(productCode);
Console.WriteLine("After->Product Id:{0}", productCode);
Console.WriteLine("");
Console.WriteLine("= = = = = = = = =");
Console.WriteLine("");
Console.WriteLine("Before->Customer Name: {0}", newCustomer.Name);
//Calling the static method to change the customer name
UpdateReferenceValue(newCustomer);
Console.WriteLine("After->Customer Name: {0}", newCustomer.Name);
Console.WriteLine("");
Console.WriteLine("= = = = = = = = =");
}
//Value type example
public static void UpdateValue(int someValue)
{
someValue = 204;
Console.WriteLine("Value changed in this method:{0}", someValue);
}
//Reference type example
public static void UpdateReferenceValue(Customer newCustomer)
{
newCustomer.Name = "Doug cooper";
Console.WriteLine("Value changed in this method:{0}", newCustomer.Name);
}
}
In the above code snippet we declared 2 variables an integer and a customer object types. Let’s try to understand the basics what happens in the above example.
Typically, In your laptop / desktop computer’s memory (RAM) some space is allocated for the above 2 variables, the illustration looks like below.
Value Type:
The system stores the value 104 in the location allocated for the variable productCode. When you pass a value type as a argument to method, the system creates a separate copy of that variable in that method, If we change the value inside a called function, the outer variable value does not change.
ClickHere to see full list of value types supported in C#.
Reference Type:
The system stores the value John Doe in one location in memory and points the memory location to the variable customerName. When you pass reference type as a argument to another method, the runtime framework does not create copy, instead it sends the variable address, so If we change the value of that variable in side the called method, the value also get’s updated in the calling method.
In simple terms, the reference type variable holds a pointer to another memory locations that contains the actual data.
ClickHere to see full list of reference types supported in C#.
Run the above example with the below C# editor.
Hope this helps you and comes a quick handy tip at your work. Thank you and see you with next tip.
Please leave any feedback in the comments area. Happy Learning 🙂
Comments are not allowed for the posts older than 30 days.
Please Click Here to contact me if you have any questions.