George Anastasov George Anastasov -4 years ago 80
C# Question

The right way to define a custom object properties?

I am currently defining custom object properties as follows:

private int count;
public int Count
{
get { return count; }
set { Count = value; }
}


my fist part of the question is there any difference between defining fields like that and like:

private int count;
public int Count {get; set;}


unless you want to check something about the value as so:

private int count;
public int Count
{
get { return count; }
set
{
if (value >= 0)
{
count = value;;
}
else MessageBox.Show("Value is negative", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}


And the second part is is there a better way of defining object properties in C#?

Answer Source

In your first example you define a private field and a property to access it. In your second example you define a private field and an auto-property that has its own backing field. So yes, there is a difference.

Unless you need custom get/set logic as in your final example, I would use the auto-property. However you shouldn't have a separate backing field (since it is independent of the property) so your code would just be:

public int Count {get; set;}

In either case (full or auto); you are using the correct way of defining properties in C#. The only thing I would add is that if you have get only properties, you can use expression-bodied members in C#6+:

public string Title => "Title"; //basically public string Title {get;} = "Title";

This is can be more efficient then the similar property because it doesn't use a backing field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download