Raspi Surya Raspi Surya - 2 months ago 10
C# Question

get set property usage

I am a bit confused with the get set property in C#.

I have the simple code below:

using System;

class Example
{
int _number;
public int Number
{
get
{
return this._number;
}
set
{
this._number = value;
}

}
}

class Program
{
static void Main()
{
Example example = new Example();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}


The code above using get set properties. However, if I delete the get set code like below code, the results stay the same.

using System;

class Example
{
int _number;
public int Number;
{


}
}

class Program
{
static void Main()
{
Example example = new Example();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}


My query is, what is the get set code used for? In the above program, the results are same. Can you give me some simple code which show the get set usage?

Answer Source

In your code, Number is simply a public field, as evidenced by the semicolon (;) at the end.

public int Number;

It is not a property, you just have an empty set of brackets right underneath which led to your confusion. If you were to remove the ; then you would actually have a property that is missing it's get, and would not compile at all.

All properties need to have a getter (setters are optional). If you want to avoid writing them, you can use auto properties, which take care of the backing field without you having to get involved:

public int Number { get; set; } // No field required

Note: A common usage pattern you'll see involving auto properties is the following:

public int Number { get; private set; }

This allows for properties that can be read from anywhere, but can only be modified from within the class they belong to.

EDIT: To answer your question, the main difference between fields and properties is in encapsulation. You can read more about the general differences between fields and properties here.

However, the example you have given has one additional difference, the private set. A normal field can be written from and to throughout the program. A property with a private setter however can only be modified from inside the class it belongs to.

Example:

public class Foo
{
    public int Id { get; private set; }
    public string Name;

    public Foo()
    {
        this.Id = 1; // This works!
    }
}

Here, Name is a field and Id is a property with a private setter. Notice that we modify Id in the constructor and that works, because it is within the class Id belongs to. Moving outside the class however:

var foo = new Foo();

// Field (no get and set):
foo.Name = "test" // Works
string bar = foo.Name; // Works

// Property (get and *private* set)
int i = foo.Id; // Works, because get is public
foo.Id = 2; // Doesn't work, because set is private