Skip to content
loading...

re: Are properties harmful? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: I don't know C# or what you mean by automatic properties, so I guess I can't follow that one :/
 

In C#, properties are just special methods which have a "get" and a "set" component. They technically don't have to do anything in particular, but the traditional old-fashioned way to write them is to wrap the getter and setter around a field:

public class Foo {
    private string _name; // This is a field
    public string Name { // This is a property
        get { return _name; }
        set { _name = value; }
    }
}

This is clearly redundant and a lot of unnecessary typing. So they introduced "auto-properties", where the following is just syntatic sugar for the above - absolutely identical result:

public class Foo {
    public string Name { get; set; }
}

You may ask, why don't you just have a public field, like:

public class Foo {
    public string Name;
}

You can do that, but what happens later when you realize that you always want the Name value to be upper-case? You would have to make a change to the structure of the class, which could potentially break other things. If you went the property way, you could simply change the "setter", and the code structure would be identical, just a change to the implementation:

public class Foo {
    private string _name;
    public string Name {
        get { return _name; }
        set { _name = value.ToUpper(); }
    }
}

The equivalent way of doing this with methods is:

public class Foo {
    private string _name;
    public string GetName() { return _name; }
    public string SetName(name) { _name = name.ToUpper(); }
}

Which isn't really bad, but it does make it a little bit more difficult to distinguish between methods that are strictly about accessing data, vs. methods that actually "do" something. Plus, like in my answer, you'd have to do even more work to serialize an object into something that returns {"Name":"John Doe"}, when the property way just "works".

code of conduct - report abuse