What is the difference between a property and a variable

C#

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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
    }
}

Solution 4 - C#

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).

Solution 5 - C#

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.

Solution 6 - C#

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://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-3.0/ms182141(v=vs.80)

Solution 7 - C#

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;
       }
   }
}

Solution 8 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVijjendraView Question on Stackoverflow
Solution 1 - C#ArcturusView Answer on Stackoverflow
Solution 2 - C#cdhowieView Answer on Stackoverflow
Solution 3 - C#user3376708View Answer on Stackoverflow
Solution 4 - C#Tomas JanssonView Answer on Stackoverflow
Solution 5 - C#AamirView Answer on Stackoverflow
Solution 6 - C#AyushmatiView Answer on Stackoverflow
Solution 7 - C#RobView Answer on Stackoverflow
Solution 8 - C#YashView Answer on Stackoverflow