0

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#?

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
EnvelopedDevil
  • 658
  • 1
  • 13
  • 29
  • 2
    Doesn't get better than `public int Count {get; set;}` – mxmissile Mar 23 '17 at 20:28
  • I'm voting to close this question as off-topic because all of this is explained in official documentation. Consult that first https://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx – Jeroen Vannevel Mar 23 '17 at 20:34

1 Answers1

2

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.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • Strictly speaking the expression-bodied property isn't exactly equivalent to `public string Title { get; } = "Title"`. The latter will result in a readonly backing field that will store the string `"Title"` while the former won't create a backing field. – Kyle Mar 23 '17 at 21:06
  • @Kyle Thanks, modified to reflect that. – BradleyDotNET Mar 23 '17 at 21:13