Why can't we use public fields for data binding in C#?

后端 未结 3 1919
暖寄归人
暖寄归人 2021-02-13 15:10

I am aware of the advantages of using properties over fields, like being able to provide additional logic when required in the future.

But I really wonder why it\'s not

3条回答
  •  迷失自我
    2021-02-13 16:09

    The short version is that always using properties instead of public (or, really, even protected) fields has been a fundamental design choice in .NET since the very beginning.

    The slightly longer version is that adding support for public fields would add complexity to the data binding framework (whichever one you're referring to). Fields also lack any kind of support for change notification, which is a fairly important aspect of data binding (at least in a stateful environment like Winforms development). Even at the level of retrieving and setting values, fields and properties are different; while the syntax in VB.NET or C# for retrieving or setting the value of a property is (by design) the same as that of a field, the mechanism used to do this in a programmatic scenario like data binding is different for properties vs. fields.

    In the end, this all just means that it would take more work to add support for public fields to any data binding scenario, so since it's an anti-pattern anyhow this work isn't done.

提交回复
热议问题