Justify Objects are of Reference types


This post is especially for .net newbies , In this article I will justify how objects are reference types, We would have learnt that objects and strings are references types, Lets practically see how objects are reference types.

Before heading to the illustration lets know about refrence types are value types:

Refrence types are always allocated on Heap data structure .
Reference types are string,class,objects,interface and delegates
Reference types support Inheritance


Value types are always allocated on Stack data structure .
Value type data type are bool, byte,int, decimal, uint,float,Double and char
Value types does support Inheritance




class Program
{

public class Class1
{
public string a;
}


static void Main(string[] args)
{
Class1 object1 = new Class1();
Class1 object2 = new Class1();
object1.a = "new string";
object2.a = object1.a;
object2 = object1;
object1.a = "updated string";
Console.WriteLine("Value of object1: {0}", object1.a);
Console.WriteLine("Value of object1: {0}", object2.a);
Console.ReadLine();


}
}



In the above code I am creating two objects of a Class carrying a string.
I copy object1 to object2, later i modify only object1.a which also reflects object2.a

When we run the above code we can see that the value of object1.a also chages to "updated string" though we didnt copy it from object1.a.

objects are reference type


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: