Urgent:Why output different in String and class?Why different behavior?

Dec 1 2004 10:20 AM
We know there are 2 categories of datatypes in C#: Value type and reference type String and Class both are refernce types. I have made 2 program in C# using each of them but got different outputs. Code using String: string s1="amit"; string s2=s1; Console.WriteLine("Before s1={0}",s1);//Output is: amit Console.WriteLine("Before s2={0}",s2);//Output is: amit s2="shilpi"; Console.WriteLine("After s1={0}",s1);//Output is: amit Console.WriteLine("After s2={0}",s2);//Output is: shilpi ---------------------------------------------------------------------- Code using Class: using System; class class1 { private int num; public int Num { get { return num; } set { num=value; } } } class mainclass { public static void Main() { class1 c1=new class1(); class1 c2=new class1(); c1.Num=100; c2=c1; Console.WriteLine("Before c1={0}",c1.Num);//output is 100 Console.WriteLine("Before c2={0}",c2.Num);//output is 100 c2.Num=200; Console.WriteLine("After c1={0}",c1.Num);//output is 200 Console.WriteLine("After c2={0}",c2.Num);//output is 200 } } ---------------------------------------------------------------------- In string case: when s2 is changed, s1 is not affected In Class case: when c2.value is changed, c1.value is also changed Why their behaviour is different?

Answers (6)