Is there any benefit to write a Property with a private variable ?
Why:
may be better than:
if we let get and set public ?
26 Replies
in most IDEs, you get that useful '1 usage' tag above properties, but not fields
additionally, properties are required for a lot of frameworks that require attributes over methods -- such as MVVM frameworks and serialization
I think that the easiest way to see the reason is to understand that not always you'll just get/set the same value.
For example:
In this case, you return a String, but what you have is an integer
I know that, my question was about if I take the exact same value
Yes. It's exactly the same value
I forgot about that point, you are right !
dp, they mean in the degenerate case where it's the same type with public get/set
There can be difference in some methods calls between variable and properties ? š¤
The most important part is "because now you can change it without breaking things later"
a very good point
And is there any convention for when we must use variable instead of property ?
The convention is always use properties for public things
fields for private implementation details, properties for publicly-exposed stuff
in normal C# at least. in unity, its different
š š
So 'get; set;' without associated private variable is good too ?
yep, absolutely fine
it's equivalent to writing it out the long way
š
you only need the private field if you do more complex stuff
I'd say in unity properties are still preferred, you just can't really use auto properties if you want to serialize
Like read-only Property ?
nope, you can do
public int MyProperty { get; }
by itself just fine
i mean like thisOh I was thinking about
private set;
but it's the same, my bad
contrived example, but yeah
Invoke some event on set . Eg
Will this not trigger an infinite loop when setting Name ?
ah yes, fixed
Okay, I unserstand ! Thanks š