Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# autoproperty vs normal fields [duplicate]

is there any effective difference between Foo.Something and Bar.Something in this example?

class Foo
{
    public string Something;
}

class Bar
{
    public string Something{get; set;}
}

class Program
{
    static void Main(string[] args)
    {
        var MyFoo = new Foo();
        MyFoo.Something = "Hello: foo";
        System.Console.WriteLine(MyFoo.Something);

        var MyBar = new Bar();
        MyBar.Something = "Hello: bar";
        System.Console.WriteLine(MyBar.Something);
        System.Console.ReadLine();
    }
}

AFAIK they behave exactly the same. If they do why not to use plain Fields like in Foo? In java we use setters to be able enforce new invariants without breaking code and getters to return safe data but in c# you can always rewrite Foo into this:

class Foo
{
    private string _Something;
    public string Something
    {
        get { 
            //logic
            return _Something; 
            }
        set { 
            //check new invariant
            _Something = value; 
            }
    }
}

And old code will not be broken.

like image 364
adekcz Avatar asked Mar 21 '13 14:03

adekcz


1 Answers

AFAIK they behave exactly the same.

No they don't.

  • Fields can't be used in data binding (at least in some binding implementations)
  • You can add more logic later for properties without breaking source or binary compatibility
  • Properties can't be passed by reference
  • You can't add an initializer to an automatically implemented property
  • They'll clearly be different in terms of reflection
  • Philosophically, properties are logically part of the API whereas fields are an implementation detail

in c# you can always rewrite Foo into this: [...]

Well you can if you don't care about binary or source compatibility, yes. In some cases that's really not an issue - in other cases it's very, very much an issue. Why not make the choice to expose your API rather than your implementation details from the start? It's not like adding { get; set; } in your code is adding much clutter...

For more ranting, see my article on this.

like image 95
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet