I read a zillion articles on Auto Properties and can’t come up with a reason for NOT doing something like the following example. Am I missing something here; i.e. is there any reason I should use regular properties in this example? I do it regularly and it works fine.
In a different thread here on StackOverflow ( C#3.0 Automatic properties with extra logic ) the answer was declared to be No as in “No, automatically implemented properties have no declared implementation. Any extended implementation that you wish to provide would have to use a regular property.”
class Foobar
{
public string Description { get; set; }
public bool Scary { get; private set; }
public void Describe(int size)
{
if (size <= 3)
{
switch (size)
{
case 1:
Description = "Cute";
Scary = false;
break;
case 2:
Description = "Interesting";
Scary = false;
break;
case 3:
Description = "Interesting";
Scary = false;
break;
}
}
else if (size > 4 && size < 10)
{
Description = "I'm sweating!";
Scary = true;
}
else
{
Description = "I'm outta here - every man for himself";
Scary = true;
}
}
}
You’re not adding code to the get/set methods for your properties, you’re adding an entirely separate method to the class which uses the get/set properties.
If someone uses the set methods for
DescriptionorScarydirectly, rather than usingDescribe, no custom logic is executed. As an example, nothing prevents someone from doing:obj.Describe(10); obj.Description = "Cute";. If you overloaded thesetmethod for those properties you could prevent someone from creating such a cute and scary object.The answer in the question that you’ve linked to is perfectly correct; you cannot add validation to the get/set methods of an auto-implemented property; if you want to you need to explicitly define the get/set methods.