difference between a normal variable and one declared with that property shorthand garbage
i'd be grateful for anyone willing to explain that to me.
Like, I encountered it while trying to set up a DataGrid in WinUi earlier and changing a class property from normal public field to one with the get set shorthand fixed it for some reason and i'm just wondering why they behave differently. aren't they accessed the exact same way from the outside?
18 Replies
Let me get this straight: You don't understand something, and you go about calling it garbage, and you expect a positive response?
long story short, properties are methods, not data, even though they look like data
that's the cause of all the differences
who gets offended on behalf of a programming language feature
ah so the shorthand just makes the field private and a public property with the same name in the background?
as a extra, would you happen to know why xaml bindings only work with properties?
what exactly do you mean with "the shorthand"?
public string Blarg => "meep"
?
public string Blarg { get; set; }
?
[ObservableProperty]private string _blarg;
?{get; set; }
thats just an auto-property
the compiler will generate a backing field for you
well as Becquerel said, properties are methods
that means you can have those methods do other things than just return data
like, notify listeners that something changed
i see
they're accessed exactly like regular fields tho right?
yes, syntax wise
just that when you change or read the value some function gets called in the background
yes
in general for C#, any data that is not private should be exposed via a property
public fields are very rarely used these days
I can't think of a single valid usecase for a public field outside extreme performance
do you know this perchance?
i'm really just curious what difference it makes to winui
it's what pobiega said about 'notifying listeners that something changed'
the xaml ui frameworks rely on INotifyPropertyChanged to update their UIs
fields don't have the power to tell other code when they change
do they inject stuff into the property methods?
like, to do the notifying
you need to do that usually
often with an attribute
depends on the framework
or inherit from some base class which does it for you
I have never used winui, but in WPF you do it yourself. Community Toolkit has that lovely source generator that helps you do it very easily
that is pretty cool
thank you 2
you have been very helpful
I think its because of the convention of "properties for anything public"
the JSON serialiser from STJ ignores fields by default too
that is good to know