I need to do a minor check in C# setter - check if property is an empty string. Right now I ended up with structure like that:
private string property;
public string Property
{
get
{
return property;
}
set
{
if (value.IsNotEmpty())
{
property = value;
}
}
}
Instead of
public string Property { get; set; }
6 lines instead of 1. Is there a way to insert the logic, but keep it condensed and elegant?
No
Auto-properties (or the "short form") can have access modifiers, but no logic. You are stuck with the code you have.
One thing you could do is to encapsulate your string
in an object that allows for an implicit cast from string (and to string), and checks IsNotEmpty
before assigning to a underlying value. Also not the most elegant solution, but it would probably allow you to keep the syntactic sugar.
No, there is no syntax sugar for such cases (at least up to C# 5.0 - current for 2014).
You can format them differently and use ?:
instead of if
if it looks nice enough to you:
public string Property
{
get { return property; }
set { property = value.IsNotEmpty() ? value: property;}
}
It's not exactly what you ask, but perhaps you can use DataAnnotations, for not allowing an empty string. Something like this, in this case a validation exception is raised if the property is null, an empty string (""), or contains only white-space characters.
[Required]
public string Property { get; set; }
As of C# 7, properties support arrow syntax, making the following possible:
private string property;
public string Property
{
get => property;
set => property = value.IsNotEmpty() ? value : property;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With