In C#, if I have the following code:
public int VarName { get; set; }
Will
VarName
still be a value type?Will any boxing or unboxing occur?
Is there any overhead for storing references relating to get / set?
In C#, if I have the following code:
public int VarName { get; set; }
Will VarName
still be a value type?
Will any boxing or unboxing occur?
Is there any overhead for storing references relating to get / set?
Yes, it will still be a value type.
No, there won't be any boxing or unboxing (since you're not treating it as an Object).
And no, there is no overhead since you're not storing references relating to get/set. It simply stores the int in a compiler generated backing field.
The getter and setter are actually methods and not fields. They will set a backing field of type int (that is a value type) and return that same backing field.
However the compiler (at least the Microsoft one) will optimize this code, and make the method call to the getter and setter inline, so that the performance between the property, and using a public field is the same.
It's always preferred to use a property instead of a public variable in a class. A good reason for this is that if you suddenly needs to make some validation when setting the variable, you can do so without changing any code calling the class, and it also makes it possible to only have the getter public, so that any subscriber to your class can only get the value and not set it.
Will VarName still be a value type?
Yes.
Also will any boxing or unboxing occur?
No, because there's no conversion between a reference type and a value type.
Is there any overhead for storing references relating to get / set?
No. The C# compiler automagically generates optimized get and set methods, which do nothing but retrieve and set, respectively, the value of a compiler generated variable. It's generally better to expose variables as properties rather than public fields so that things like data binding work right, and just as a general best practice.
yes , it will , but if it is a property of a class , it will go on heap and also no boxing and unboxing will occure until you explicitly do it in your code.