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.
AFAIK they behave exactly the same.
No they don't.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With