1

I am pretty new to OOP and looking into things in a bit more depth, but I have a bit of confusion between these 3 methods in C# and which one is best and what the differences are between 2 of them.

Example 1 So lets start with this one, which (so I understand) is the wrong way to do it:

public class MyClass
{
    public string myAttribute;
}

and in this way I can set the attribute directly using:

myObject.myAttribute = "something";

Example 2 The next way I have seen and that seems to be recomended is this:

public class MyClass
{
    public string myAttribute { get; set;}
}

With getters and setters, this where I dont understand the difference between the first 2 as the variable can still be set directly on the object?

Example 3 The third way, and the way that I understand the theory behind, is creating a set function

public class MyClass
{
    string myAttribute;
    public void setAttribute(string newSetting)
    {
        myAttribute = newSetting;
        //obviously you can apply some logic in here to remove unwanted characters or validate etc.
    }
}

So, what are the differences between the three? I assume example 1 is a big no-no so which is best out of 2 and 3, and why use one over the other?

Thanks

Sam Leach
  • 72
  • 7
  • 5
    See [What is the difference between a field and a property in C#?](http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c). Fields are supposed to remain private, you expose properties using getters and/or setters. See also the [Fields](http://msdn.microsoft.com/en-us/library/ms173118.aspx) and [Properties](http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx) chapters in the C# Programming Guide on MSDN. – CodeCaster Oct 15 '13 at 08:33

4 Answers4

3

The second

public class MyClass
{
  public string MyAttribute { get; set;}
}

is basically shorthand for:

public class MyClass
{
  private string myPrivateAttribute;

  public string MyAttribute 
  { 
     get {return myPrivateAttribute;}
     set {myPrivateAttribute = value;}
  }
}

That is an auto-implemented property, which is exactly the same as any regular property, you just do not have to implement it, when the compiler can do that for you.

So, what is a property? It's nothing more than a couple of methods, coupled with a name. I could do:

public class MyClass
{
  private string myPrivateAttribute;

  public string GetMyAttribute()
  { 
     return myPrivateAttribute;
  }

  public void SetMyAttribute(string value)
  {
     myPrivateAttribute = value;
  }

}

but then instead of writing

myClass.MyAttribute = "something";
string variable = myClass.MyAttribute;

I would have to use the more verbose, but not necessarily clearer form:

myClass.SetMyAttribute("something");
string variable = myClass.GetMyAttribute();

Note that nothing constraints the contents of the get and set methods (accessors in C# terminology), they are methods, just like any other. You can add as much or as little logic as you need inside them. I.e. it is useful to make a prototype with auto-implemented properties, and later to add any necessary logic (e.g. log property access, or add lazy initalization) with an explicit implementation.

SWeko
  • 30,434
  • 10
  • 71
  • 106
  • You can also apply some logic inside get and set blocks, so I prefer the second example as it is very convenient (public string myAttribute { get; set;}) – dave Oct 15 '13 at 08:37
  • Thanks, so Examples 2 and 3 are basically the same but the compiler implements it so its cleaner to write? But why use example 2 over example 1 then if it is just publicly setable anyway? – Sam Leach Oct 15 '13 at 08:44
  • @SamLeach: No, `myPrivateAttribute` is **not** publicly setable, even if there is a method that just set it. That method can change, without requiring the change of any code that calls it. E.g. even if I always keep the front door unlocked so anyone can enter, it's not smart to just remove the door, because that also removes the option to lock the door. – SWeko Oct 15 '13 at 09:01
  • @SamLeach Properties have the benefit that you can easily change them later on without breaking the interface. For example if you want to add some validation to the property setter (so that you cannot set it to invalid values), you can easily do that if you already have a property. You just need to change the implementation of the property, but you don’t change the interface. Fields on the other hand (example 1) are always fields, and cannot have any logic. So you would have to change it into properties, which would result in an interface change breaking dependent code. – poke Oct 15 '13 at 09:03
  • so although it still is set by using `.myAttribute = "something";` this is a property instead of just a field? so later on I can expand example 2 so the setter applies some logic? – Sam Leach Oct 15 '13 at 09:15
  • 1
    Yes, if you use example 2, i.e. the auto-implemented properties, you can later replace that auto implementation by your own getter and setter implementation, adding custom logic, without breaking existing code. On the outside, it will still be a property and nothing changes there. – poke Oct 15 '13 at 09:18
0

What your asking here has to do with encapsulation in OOP languages.

The difference between them is in the way you can access the propriety of an object after you created an object from your class.

In the fist example you can access it directly new MyClass().MyAttribute whether you get or set it's value.

In the second example you declare 2 basic functions for accessing it:

public string MyAttribute 
{ 
   get {return myPrivateAttribute;}
   set {myPrivateAttribute = value;}
}

In the third example you declare your own method for setting the value. This is useful if you want to customize the setter. For example you don't want to set the value passed, but the value multiplied by 2 or something else...

I recommend some reading. You can find something here and here.

Razvan
  • 3,017
  • 1
  • 26
  • 35
0

Property is a syntactic sugar over private attribute with get and set methods and it's realy helpful and fast to type;

You may treat automatic property with { get; set;} as a public attribute. It has no additional logic but you may add it later without uset ever notice it. Just exchange

public string MyLine { get; set;}

to

string myLine;
public string MyLine 
{
    get { return myLine; }
    set { myLine = value + Environment.NewLine;  }
}

for example if you need so.

You can also easily create read only property as { get; private set }.

So use Properties instead of public attributes every time just because its easier and faster to write and it's provides better encapsulation because user should not be used get and set methods if you decide to use it in new version of yours programm.

Deadcow
  • 111
  • 2
  • 8
0

One of the main principles of OOP is encapsulation, and this is essentially the difference between the first example and the other 2.

The first example you have a private field which is exposed directly from the object - this is bad because you are allowing mutation of internal data from outside the object and therefore have no control over it.

The other 2 examples are syntactically equivalent, the second being recommended simply because it's less code to write. However, more importantly they both restrict access & control mutation of the internal data so give you complete control over how the data should be managed - this is ecapsulation.

James
  • 80,725
  • 18
  • 167
  • 237