Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Value type & Reference type

Status
Not open for further replies.

ganmath

Technical User
Apr 5, 2001
1
US
What is the difference between value type & Reference type ?????


Can any body explain with examples???????


 
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.

Refer Jeffrey Richters excellent article
 
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


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top