简体   繁体   中英

Is a value-type with getters and setters still a value-type?

In C#, if I have the following code:

public int VarName { get; set; }
  1. Will VarName still be a value type?

  2. Will any boxing or unboxing occur?

  3. 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.

是的,它会,但是,如果它是一个类的属性,它将继续堆放,并且也不会发生装箱和拆箱,直到您在代码中显式地进行装箱为止。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM