Why is it desirable to use all properties instead of public instance variables in C #?

I know that properties have some advantages, but if you think that you do not need a property, what harm does it make public?

People say that changing the public field to a property will lead to code breaking if you try to do it later, but in my experience changing it to a property will not break anything.

+4
source share
4 answers

I think people mean that it violates ABI (binary) compatibility, not API (source code) compatibility.

Although the syntax is identical, behind the scenes, access to properties and access to member variables compiles differently.

However, if your variable / property is not used from an assembly that you yourself are not compiling, then there is no harm in changing it. But if it is part of an open interface, then it is better to make it proprietary so that you do not regret it in the future.

+7
source

This is about supporting both binary and source compatibility . For some time in the future, you may decide to make the assignment logic more complex and change the fields to properties. This is where the problems arise.

  • Common fields can be used as out and ref parameters. Properties cannot. This will result in incompatible code.

  • Various reflection methods are used to access fields and properties. This means that any code that receives or sets values ​​using Reflection will break, and you will only know about it at runtime.

  • Different IL operators are used to access fields and properties. This means that failure assembly compatibility is interrupted when fields are changed to properties, and only one assembly is recompiled. This will cause your program to crash at runtime.

+2
source

I agree with you if the property is just a wrapper on the field. And the guys from Coding Horror look the same as our opinion, I find it very funny that they use a scared icon :) http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables. html

0
source

A simple program.

Here I add two properties and one variable. We can use properties according to our decision. But I prefer to use properties because it helps to implement some health check and can hide the calling side of the business logic form.

 class Program { static void Main(string[] args) { Human h = new Human(); h.FirstName = "Test"; h.LastName = "User"; Console.WriteLine(h.FullName); Console.Read(); } } class Human { public string FullName { get { return FirstName + " " + LastName; } } public string FirstName;//{ get; set; } public string LastName;//{ get; set; } } 
0
source

Source: https://habr.com/ru/post/1490451/


All Articles