-2

Hello what is difference between this field:

public string Name;

And this property:

public string Name{get;set;} 

I read this topic :

What is the { get; set; } syntax in C#?

  • 4
    The first is a **field** (**not** a property). The second is an auto-implemented property (basically a getter and setter, with a "hidden" backing field). https://stackoverflow.com/questions/1180860/public-fields-versus-automatic-properties – mjwills Jun 18 '21 at 23:02
  • Encapsulation. In the second instance you've just defined a variable, in the first, there is a getter / setter around the variable. So if you decide you want to validate the variable at a later date - it will be a lot easier. – zolty13 Jun 18 '21 at 23:06

1 Answers1

3

This one is just a field, which is what you call a variable that is declared directly on a class or struct:

public string Name;

This one is a property:

public string Name { get; set; } 

They are functionally similar. The getter and setter allow you to customize what happens when the variable is accessed or set, respectively. Traditionally, a property is used to expose a private field that is used inside the class to do work. You do this to expose the variable without allowing people to reach in and change or break the inner workings of the class.

This is part of Encapsulation.

In this particular syntax you are "auto-implementing" the getter and setter, which creates a hidden backing field that you never see anywhere in your code. The result is that working with this will seem extremely similar to just using a field.

Why not just use a field in this case? Aside from leading to better design, there are important implications that have more to do with convention. In a lot of cases where data binding is involved, for example, only properties are considered for binding. Fields are ignored. So in Entity Framework, a property might represent a column in a database... And it has to be a property. It cannot be a plain field.

The key lesson here is that if you want to expose a field outside you class, you should use a property to promote encapsulation and to signal to others (people and also code in some cases) that you really did intend to expose what you exposed.

More: What is the difference between a field and a property?

Brian MacKay
  • 31,133
  • 17
  • 86
  • 125