Value types are simple types like enums, structs and datatypes like int, char. They are created on the stack and directly contain data. They are state based.
Reference types are complex types like classes, interfaces, delegates. They are created on the heap and are accessed indirectly by reference variables. They are behaviour based.
All types (both value and reference) inherit from OBJECT superclass. Primitive types can be cast to Ref. types by boxing them.
Value Type is the way classic C & C++ works when passing a variable to a function, without any specific modifiers. Primitive data types, enums, structs and even objects would fall under this category for C++ BUT IN C# only primitive data types, enums and structs are treated as VALUE TYPES.
Take an example in C#
using System;
class Test
{
static void Main()
{
int x = 10;
funCalled(x);
Console.WriteLine(x); //will print 10
}
void funCalled(int x)
{
x = 200;
/*This is value type, wherein the x in this function is a NEW variable created in the stack for this function only, which means that the value changed here will not be affecting the calling function*/
}
}
BUT since JAVA came in place, reference types got introduced, in Java & C# OBJECTS are by default passed as REFERENCES
Take another example in C#
using System;
class SomeObject
{
public int value;
}
class Test
{
static void Main()
{
SomeObject x = new SomeObject();
x.value = 10;
funCalled(x);
Console.WriteLine(x.value); //will print 200
}
void funCalled(SomeObject x)
{
x.value = 200;
/*This is a refernce type, wherein the x in this function is only REFERRING to the same object in the memory, like an alias, which means that if the value is changed here, it will be affecting object in the the calling function*/
}
}
A C++ programmer can think of reference types as the way we work with POINTERS TO OBJECTS
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.