This sample code is from MSDN.

private string name;
public string Name
{
   get 
   {
      return name; 
   }
   set 
   {
      name = value; 
   }
}

I looked several examples, and they are the same. Why do we keep two different properties to store the name, namely "name" and "Name".

I mean, why don't we write the code like this?

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

Dani AI

Generated

Short answer: the public property (e.g. Name) is the access surface and the private field (e.g. name) is the actual storage. Using the property inside its own getter/setter (like returning Name from get) causes infinite recursion and eventually a StackOverflowException — the second snippet in 's post shows that pitfall. Properties are compiled into accessor methods (get*/set*), not into raw storage.

Why keep both? Fields are simple storage; properties are the public API that can:

  • validate or transform values,
  • expose different accessibility (public get / private set),
  • raise events (INotifyPropertyChanged) for data binding,
  • present a stable API to serializers and callers while implementation can change later.

For simple pass-through storage there are compiler-generated backing fields (auto-properties) and property initializers, so a separate field is not always needed. For example, to give a default and make the property set only during construction:

public string Name { get; init; } = "Unnamed";

(The init accessor is useful for immutable-style objects.)

Naming and best practices: prefer PascalCase for public properties and _camelCase for private fields (for example _ipLocal). Avoid exposing fields publicly. Keep accessors cheap and side-effect free — heavy or slow work belongs in methods. When a setter must do validation or notify listeners, do that there; otherwise prefer an auto-property.

Troubleshooting tips: when a property "doesn't work" check for accidental recursion, shadowed/local variables, or multiple declarations. For typed members (like IPAddress) prefer exposing the typed property and add a separate string wrapper/property for parsing/serialization if needed. and already touched on the key tradeoffs — use a backing field only when logic or compatibility requires it.

Recommended Answers

All 6 Replies

I kept looking for examples about this matter after posting the message above, I realized that there is no way of assigning initial values to "Name" property without declaring a second one (the "name" property).

Is the reason to define two different variables for being able specify default values?

In newer versions of .Net you can declare properties like this:

// For a simple property (this is useful because properties 
// are thread safe)
public int MyInt{get; set;}

// To allow it to only set with the current class but viewable outside
public int MyInt{get; private set;}

The above are useful but properties can also be used to do simple conversion or other logic within the get{} and set{} parts though it should be noted that it is not a good idea to put anything complex inside here especially if you are going to use reflection.

public string MyText
{
    get
    {
            return myMask.Complete ? myMask.Text : "Invalid Text";
     }
}

This is my code:

private System.Net.IPAddress m_IpLocal = null;
public string m__IpLocal
{
    set
    {
        m_IpLocal = System.Net.IPAddress.Parse(value);
    }
}

Now I understand the most of the mechanism behind this "get" and "set".

Is there any naming standard for naming these two properties? I used m_IpLocal[icode] and m__IpLocal (double underscores).

Thanks in advance.

Most people don't use this kind of hungarian type notation much anymore, generally .Net developers tend towards using names starting with caps as in my example for properties and lower case for local variables. I do use a leading underscore for member variables but even that is somtimes frowned upon.

If I where you I would add a get{ return ipAddress.Tostring; } as it will probably make it easier to use.

The property "Name" is the syntactic sugar that allows you to fluently set or obtain the value of the backing field, "name." In other languages, you would not typically have such a property, you would have distinct getter and setter methods for working with the value.

private string name; 
public void SetName(string input) { name = input; }
public string GetName() { return name; }

// some other code 
obj.SetName("Foo");
string bar = obj.GetName();

And, in fact, that's what is implemented in .NET under the hood when the code compiles and runs. But by being a property at design time, you're able to more intuitively work with the object, much as if you were working with just another variable.

obj.Name = "Foo";
string bar = obj.Name;

While the code from the two examples are not that different, consider another scenario where you might be storing an integer and you wanted to increment it.

// getter and setter methods
int temp = obj.GetCount();
obj.SetCount(temp + 1);

// or using a property
obj.Count++;

Back to the original, "Name" is the name of the property, the point of access to the backing field. "name" is the field where the value is stored.

As privatevoid pointed out, with C# 3+, you do not need to define such a backing field. It is referred to as "auto-implemented properties," but it works such that the compiler will automatically create the backing field for you given code like this

public string Name { get; set; }

However, if you need to do some validation or monitoring of the property, you would still need to provide your own backing field.

private string name;

// does not allow nulls
public string Name 
{
     get { return name; }
     set 
     {
          if (value == null)
               throw new Exception("Null value not allowed for property 'Name'");

          name = value;
     }
}

Thank you so much for taking your time and explaining it for me.
Your last code sample explains everything.
Thank you again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.