Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know properties have some advantages, but if you think you won't need a property, what's the harm in making it a public instance?

People say that changing the public field to a property will break code if you try to do it later on but in my experience changing it to a property breaks nothing.

like image 901
Thomas Avatar asked Jan 12 '23 23:01

Thomas


1 Answers

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

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

That said, if your variable/property is not to be used from an assembly that you yourself do not compile, then there is no harm in changing it. But if it is part of a public interface, then it is better to make it a property, so that you will not regret it in the future.

like image 115
rodrigo Avatar answered Jan 31 '23 09:01

rodrigo