CudoX
CudoX

Reputation: 1003

Why use member variables in a class

I've seen most people use member variables in a class like :

string _foo;
public string foo { get { return _foo; }; private set { _foo = value}; }

But what's the difference of that to this?

public string foo { get; private set; }

Upvotes: 5

Views: 155

Answers (4)

Khalid Farhan
Khalid Farhan

Reputation: 465

Different scenario gives various advantages.

string _FirsName;   
string _LastName;   

public string FullName 
{ 
   get 
   { 
      return _FirsName + _LastName;
   }
   set; 
} 

public string ReverseName 
{ 
   get 
   { 
      return _LastName + ", " + _FirsName;
   }
   set; 
}

Upvotes: 0

Thangadurai
Thangadurai

Reputation: 2621

Prior to the introduction of "Automatic Properties", we need to use some "backing field" for the propoerties. Most of the time the Propoerties will simply return the value / set the value to the "backing field" as in the below example.

public string Name
{
   get { return _name; }
   set { _name=value; }
}

With the introduction of 'Automatic Properties' we can simply ignore the 'backing field' (or we dont need to supply one). This is mostly suitable if your design is like the above example, but if you need to enforce some 'kind' of custom logic while retrieving the value or before setting the value, we still need to follow the 'good old design' (i.e with the backing field)

Upvotes: 1

Luaan
Luaan

Reputation: 63732

As long as the property implementation doesn't actually do anything but get and set, the difference is quite minor. The reasons for using that may be:

  • Legacy code before C# 3.0 (which added auto-properties, ie. the public string Name { get; set; } syntax.
  • Expecting to have to change the implementation of the getter / setter at some point.
  • Requirements for some custom serialization.
  • Using the underlying field in code for whatever reason. A good example might be using the backing field as a ref parameter to some method. This also includes things like using the value in native interop (GCHandle etc.).
  • Simple user preference. I don't usually use auto-properties, because I like to specify the backing fields manually.
  • Using a readonly backing field is impossible when using auto-properties.

This is just the tip of the iceberg. There are also tons of wierd reasons, say having to declare the field explicitly so that someone can access it using reflection, for whatever reason.

Upvotes: 3

Pedro.The.Kid
Pedro.The.Kid

Reputation: 2078

In simple cases like that its the same but in more complex cases where you fire events or something you need additional code in the get and set so you need the member ex:

private string _name;
public string Name
{
   get{ return _name; }
   set
   {
      SomeHandler("Name", value);
      _name = value;
   }
}

Upvotes: 4

Related Questions