namespace My_Samples { public class MyClass { public string FirstName { get; set; } public string LastName { get; set; } } public struct MyStruct { public MyClass MyClassObject; public MyStruct(string firstName, string lastName) { MyClassObject = new MyClass() { FirstName = firstName, LastName = lastName }; } } }
The above example declares a class "MyClass", and a struct "MyStruct". The MyStruct value type contains a public reference type variable of MyClass. The MyStruct has a parameterized constructor and initializes the MyClassObject variable. Now,
MyStruct s1 = new MyStruct("s1FirstName", "s1LastName"); MyStruct s2 = new MyStruct("s2FirstName", "s2LastName"); s1 = s2; s2.MyClassObject.FirstName = "s2FirstNameModified"; Console.WriteLine(s1.MyClassObject.FirstName);
We created 2 structure variables, and assigned s2 to s1. Then we modified the value of s2's reference type variable value. Now what do you expect the Console.WriteLine prints. The output will be "s2FirstNameModified".
The behavior is "When you assign the value types containing reference types, though you have 2 strcuture types but they will share the reference of the class object"
No comments:
Post a Comment