Home > Software design >  Need clarification of Class type in C# being a reference type as said in the Microsoft Docs
Need clarification of Class type in C# being a reference type as said in the Microsoft Docs

Time:09-28

The following paragraphs are from this link:

A class or a record is a reference type. When an object of the type is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.

A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it's copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy don't affect the other copy.

So far what I understand from the first paragraph is that when a class is instantiated and assigned to two different variables what you do to the other variable would reflect on both variables. On the second paragraph if a struct is instantiated and assigned to two different variables and something is done to the other the two variables would have different values because they are now two different instances.

Is my understanding correct? Does this mean that passing a class object to a method is a call by reference and passing a struct object is a call by value? If I'm wrong can someone provide a better explanation?

CodePudding user response:

Is my understanding correct?

That seem basically correct.

Does this mean that passing a class object to a method is a call by reference and passing a struct object is a call by value?

I think it it would be more correct to say that the parameters are passed by reference or value.

Also note that there is a recommendation to make structs immutable, and for immutable types there is not really much semantic difference if it is a reference or value type.

  •  Tags:  
  • c#
  • Related