What Is the { Get; Set; } Syntax in C#

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

It's a so-called auto property, and is essentially a shorthand for the following (similar code will be generated by the compiler):

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

How get set property works in C#?

Initial Problem - StackOverflow

The problem is that you are inadvertently using recursion, which is going to lead to a stack overflow, because your getters and setters for the Number property are getting and setting the Number property, rather than a backing field.

It should at the very least be changed to this:

private int number;

public int Number
{
get
{
if(this.number>10)return 10;
else
{
return this.number;
}
}
set
{
if (value > 10)
{
this.number = 10;
}
else
{
this.number = value;
}
}
}

C# Get/Set Syntax Usage

Assuming you have access to them (the properties you've declared are protected), you use them like this:

Person tom = new Person();
tom.Title = "A title";
string hisTitle = tom.Title;

These are properties. They're basically pairs of getter/setter methods (although you can have just a getter, or just a setter) with appropriate metadata. The example you've given is of automatically implemented properties where the compiler is adding a backing field. You can write the code yourself though. For example, the Title property you've declared is like this:

private string title; // Backing field
protected string Title
{
get { return title; } // Getter
set { title = value; } // Setter
}

... except that the backing field is given an "unspeakable name" - one you can't refer to in your C# code. You're forced to go through the property itself.

You can make one part of a property more restricted than another. For example, this is quite common:

private string foo;
public string Foo
{
get { return foo; }
private set { foo = value; }
}

or as an automatically implemented property:

public string Foo { get; private set; }

Here the "getter" is public but the "setter" is private.

When to use get; set; in c#

Basically, in that case, there is no difference, of the (many) advantages of using a property is the ability to add Events to your property, like so:

  public delegate void ChangedEventHandler(object sender, EventArgs e);

int m_i = 0;
public int i
{
get { return m_i; }
set { m_i = value; iChanged(self, null); }
}

public ChangedEventHandler iChanged;

This allows for code to know when I has been changed (there might be some syntax errors, I haven't focused on C# in a while, but the idea is similar). This is extremely important in winforms, as this is the major way of knowing when a button (or similar) has been clicked.


Also, this allows for additional functionality in the setter of a property, e.g. checking if it is in a certain range, like this:

  int m_i = 0;
public int i {

get { return m_i; }
set { if (value > 10) throw new Exception("I cannot be greater than 10!"); m_i = value; }
}

What is the purpose of the get and set properties in C#

They are just accessors and mutators. That's how properties are implemented in C#

In C# 3 you can use auto-implemented properties like this:

public int MyProperty { get; set; }

This code is automatically translated by the compiler to code similar to the one you posted, with this code is easier to declare properties and they are ideal if you don't want to implement custom logic inside the set or get methods, you can even use a different accessor for the set method making the property immutable

public int MyProperty { get; private set; }

In the previous sample the MyProperty will be read only outside the class where it was declared, the only way to mutate it is by exposing a method to do it or just through the constructor of the class. This is useful when you want to control and make explicit the state change of your entity

When you want to add some logic to the properties then you need to write the properties manually implementing the get and set methods just like you posted:

Example implementing custom logic

private int myProperty;
public int MyProperty
{
get
{
return this.myProperty;
}
set
{
if(this.myProperty <=5)
throw new ArgumentOutOfRangeException("bad user");
this.myProperty = value;
}
}

What does {get; set;} means ?

Using { get; set; } by itself translates exactly to what you usually use.. its just shorthand for it.

The compiler creates an automatic backing field.

So this:

public string FirstName { get; set; }

..is compiled to this:

private string _firstName;

public string FirstName {
get {
return _firstName;
}
set {
_firstName = value;
}
}

This all happens at compile time, therefore you cannot directly access the backing field (because it isn't actually available until the code is compiled).

After the compiler converts the above.. automatic properties are actually turned into methods.

So the above is turned into this:

public void set_FirstName(string value) {
_firstName = value;
}

public string get_FirstName() {
return _firstName;
}

Then some IL is produced to notify tools like Visual Studio that they are properties and not methods.. somewhat like this:

.property instance string FirstName() {
.get instance string YourClass::get_FirstName()
.set instance void YourClass::set_FirstName(System.String)
}

meaning of typing {set; get;} on a value - C#

One is property and another is a field. Equivalent of property in Java is get, set method.
So, in nutshell, "public int value" create a field/attribute in your class. Whereas "public int value { get; set; }" will create a private field/attribute and two public methods to get(read) and set(write) that field/attribute in class. So, it gives safer way to access your field/attribute.

I'm not understanding the usage of C# get; set; seems to be different from Java

When you write this (I'm using different class and property names for clarity):

public class Test
{
public string Name { get; set; }
}

that's asking the compiler to create a private field with a public property. It's equivalent to:

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

(Except the field name is autogenerated and not directly representable in C#.)

That's basically equivalent to what you'd write in Java as:

// Java
public class Test {
private String name;

public String getName() {
return name;
}

public String setName(String name) {
this.name = name;
}
}

... but clearly the C# is a lot more compact.

Basically, C#'s properties make for more readable code than having getter and setter methods as normal methods - but that's all they are, really. They're just used differently in code. The automatically implemented properties (as per the first snippet) make "trivial" properties simpler to express. In C# 6, you can write read-only automatically implemented properties too, which can be assigned to from the constructor but only the constructor.

Importantly though, you're still only making the properties part of the public API - not the fields. So if you later want to add some more logic (e.g. to have two properties derived from the same field, or something like that) you can do so without affecting either source or binary compatibility.



Related Topics



Leave a reply



Submit