How often do you see abuse of C# shorthand getters/setters?

做~自己de王妃 提交于 2019-12-05 05:31:15

I've seen it abused (in my opinion). In particular, when the developer would normally write:

private readonly int foo;
public int Foo
{ 
    get 
    { 
        return foo;
    }
}

they'll sometimes write:

public int Foo { get; private set; }

Yes, it's shorter. Yes, from outside the class it has the same appearance - but I don't view these as the same thing, as the latter form allows the property to be set elsewhere in the same class. It also means that there's no warning if the property isn't set in the constructor, and the field isn't readonly for the CLR. These are subtle differences, but just going for the second form because it's simpler and ignoring the differences feels like abuse to me, even if it's minor.

Fortunately, this is now available as of C# 6:

// Foo can only be set in the constructor, which corresponds to a direct field set
public int Foo { get; }

There is no "abuse" in simply not writing the field manually; and it is good to encourage all access via the property (not directly to the field) anyway!

The biggest problem I know of is with binary serialization, where it gets a bit tricky to change back to a regular field without making it version-incompatible - but then... use a different serializer ;-p

It would be nice if there was a "proper" readonly variant, and if you didn't need to use :this() ctor-chaining on structs, but.... meh!

I haven't seen any abuse of it. And to be honest, I don't really see what you mean, as I can't see how this syntax could be abused.

I don't think automatic properties are any worse than regular properties in regards to encapsulation.

If you mean that some developers use public automatic properties instead private fields then this is of course wrong and breaks encapsulation..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!