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.