1 Answers
Explaining Value Types and Reference Types in C#
Value Types:
Value types in C# store the actual data, and they are allocated on the stack. When a value type is assigned to a new variable or passed as a method parameter, a copy of the value is created.
Example of Value Type:
int num1 = 10;
int num2 = num1;
Reference Types:
Reference types in C# store a reference to the actual data, and they are allocated on the heap. When a reference type is assigned to a new variable or passed as a method parameter, the reference is copied, not the actual data.
Example of Reference Type:
class Person {
public string Name { get; set; }
}
Person person1 = new Person() { Name = "Alice" };
Person person2 = person1;
person2.Name = "Bob";
Understanding the difference between value types and reference types is important in C# programming to avoid unexpected behavior and optimize memory usage.
Please login or Register to submit your answer