93

I have a confusion about understanding Property and Variables

public class ABC()
{
    public int A;
    public int B { get; set; }
}

What is the exact difference between in A and B?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Vijjendra
  • 24,223
  • 12
  • 60
  • 92

8 Answers8

79

As many have pointed out, A is a field, B is a property.

The real question is, why should you care, and what to use?

I refer to a blog post of Jonathan Aneja:

(Its in VB, but it applies to C# as well ;))

So why use properties over fields, 5 reasons:

1. Fields can’t be used in Interfaces

You can’t enforce the existence of a field in an object’s public contract through an interface. For properties though it works fine.

2. Validation

While your application currently may not require any validation logic to set a particular value, changing business requirements may require inserting this logic later. At that point changing a field to a property is a breaking change for consumers of your API. (For example if someone was inspecting your class via reflection).

3. Binary Serialization

Changing a field to a property is a breaking change if you’re using binary serialization. Incidentally, this is one of the reasons VB10’s auto-implemented properties have a “bindable” backing field (i.e. you can express the name of the backing field in code) – that way, if you change an auto-implemented property to an expanded property, you can still maintain serialization compatibility by keeping the backing field name the same (in C# you’re forced to change it because it generates backing fields with unbindable names).

4. A lot of the .NET databinding infrastructure binds to properties but not fields

I’ve heard arguments on both sides as to whether or not that’s a good thing, but the reality is that’s the way it works right now. (Note from me: WPF bindings work on properties)

5. Exposing a public field is an FxCop violation

For many of the reasons listed above :)

There might be more reasons.

I would also like to point to a blog post of Jeff Atwood and conclude with a quote from it:

The really important thing to take away here is to avoid writing code that doesn't matter. And property wrappers around public variables are the very essence of meaningless code.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Arcturus
  • 26,677
  • 10
  • 92
  • 107
  • 2
    And yet, auto implemented properties cannot be used as an out parameter :/ yay c# forcing meaningless code upon us – Assimilater Aug 16 '17 at 20:39
  • Updated documentation for item 5 - CA1051: Do not declare visible instance fields https://learn.microsoft.com/en-us/visualstudio/code-quality/ca1051-do-not-declare-visible-instance-fields – Tiago Crizanto Mar 07 '18 at 14:08
  • And.. what if we don't have **any** validation at all but **just** the `public string Name {get;set;}`? Why would we ever do that instead of just `public Name String;`? I have seen that multiple places but I simply cannot wrap my head around, when that is used apart form the "it's bad practice to expose a field". IMO theres no difference there – CutePoison Oct 03 '22 at 05:58
27

A is a field, B is a property. A property is basically syntactic sugar for getters and setters. The class you have defined will be compiled into something like this:

public class ABC()
{
    public int A;

    private int backing_B;

    public void set_B(int value)
    {
        backing_B = value;
    }

    public int get_B()
    {
        return backing_B;
    }
}

Note that this kind of conversion is true for all C# properties -- accesses to ABC.B will be converted to method calls. Properties basically provide the illusion of a "variable" while actually just being a cleverly disguised pair of methods.

This is important, because it allows you to declare your own get and set method body, which can validate values or do other interesting things:

private int b;

public int B {
    get { return b; }
    set {
        if (value < 0) throw new ArgumentOutOfRangeException("value");
        b = value;
    }
}

Note that most properties will use a field to store their value. Properties seldom exist on their own, apart from fields.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
5

In C# any "variable" that has a getter and setter is referred to as a property. A variable has no getters and setters or so that is what the text books say.

My programming instructor made us have getters and setters for almost every variable that we created in Java. Even indexing variables he made us use a getter and setter if they were declared at the global class scope. I think this might have been overkill but it did get me to make getters and setters.

The real things about getters and setters are that they more than likely do more than just set an internal variable. Most setters are going to perform some type of data validation to make certain that data can be set to the variable. A getter might also check returning data for some criteria.

If your property is private and your setters and getters are public technically anyone could access your variable and change it as if they had public access to the actual variable. So, in reality, you should check your data to make certain that it is valid or some other data check.

private int myVariable;
public int myVariable 
{
    get 
    { 
       return myVariable; 
    }
    set 
    {
        if (value < 0) 
        { 
           throw new Exception("This is your exception some where else in code");
        }
        myVariable = value; //remember value is something that is
                            //declared automatically
    }
}

public string FirstName { get; set; }

The above is a shorthand way of writing the following

private string firstName;

public string FirstName
{
    get
    {
       //...code here
    }

    set
    {
       //...code here
    }
}
hemal7735
  • 321
  • 1
  • 3
  • 18
4

A property is sort of a short getter and or setter. You can add logic to the set or get of the property or make them private which means that they are not accessible from the out side, where a variable is always accessible (if it is public).

Tomas Jansson
  • 22,767
  • 13
  • 83
  • 137
3

Variable is, well, a variable.

Property is a special type of method that exposes that variable. And since it is a method, therefore, you can do some other things in it apart from just exposing the variable.

From MSDN:

The Property statement introduces the declaration of a property. A property can have a Get procedure (read only), a Set procedure (write only), or both (read-write). You can omit the Get and Set procedure when using an auto-implemented property. For more information, see Auto-Implemented Properties (Visual Basic).

You can use Property only at class level. This means the declaration context for a property must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.

By default, properties use public access. You can adjust a property's access level with an access modifier on the Property statement, and you can optionally adjust one of its property procedures to a more restrictive access level.

Community
  • 1
  • 1
Aamir
  • 14,882
  • 6
  • 45
  • 69
2

There is a very good article (link below) about using fields/variables vs Properties from Microsoft itself. Though the article essentially talks about a FxCop violation rule, it clearly defines the difference between the two and the exact usage guidelines.

An excerpt from the article:

The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. Accessing a property is as easy as accessing a field, and the code in a property's accessors can change as the type's features expand without introducing breaking changes.

Refer: https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-3.0/ms182141(v=vs.80)

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
Ayushmati
  • 1,455
  • 1
  • 13
  • 15
0

Variable is defined basically for accessing value from a class or into the same class according to their modifier assigned to those variable.

When we define a property there two methods created for single property so extra overhead is generated that is the drawback of property.

The advantages of properties is to get or set value into private variable of class.

Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
Yash
  • 1
  • 2
0

In your example A is a public field on the class ABC and B is a public property on the class ABC. Specifically, B is an auto-implemented property. What this means is that "under the hood" the compiler does some of the work for you and effectively transforms your code into:

public class ABC()
{
   private int b;

   public int A;
   public int B
   {
       get
       {
          return b;
       }
       set
       {
          b = value;
       }
   }
}
Rob
  • 45,296
  • 24
  • 122
  • 150