I am wondering if C# supports optional properties as the following
public class Person
{
public string Name { get; set;}
public optional string NickName { get; set;}
...many more properties...
}
so that when I create a Person object I can easily check the validity of input values in a simple loop
public bool IsInputOK(Person person)
{
foreach( var property in person.GetType().GetProperties())
{
if( property.IsOptional())
{
continue;
}
if(string.IsNullOrEmpty((string)property.GetValue(person,null)))
{
return false;
}
}
return true;
}
I have searched on google but didn't get desired solution. Do I really have to hand code validation code for each property manually?
Thanks.
You can decorate these properties with attribute you define and mark the properties as optional.
[AttributeUsage(AttributeTargets.Property,
Inherited = false,
AllowMultiple = false)]
internal sealed class OptionalAttribute : Attribute
{
}
public class Person
{
public string Name { get; set; }
[Optional]
public string NickName { get; set; }
}
public class Verifier
{
public bool IsInputOK(Person person)
{
foreach (var property in person.GetType().GetProperties())
{
if (property.IsDefined(typeof(OptionalAttribute), true))
{
continue;
}
if (string.IsNullOrEmpty((string)property.GetValue(person, null)))
{
return false;
}
}
return true;
}
}
You may also want to take a look at Validation Application Block which has similar capabilities out of the box.
C# does not have an 'optional' keyword, and as @Mitch Wheat says, it's a horrible way to perform validation.
Why can't you just do the validation in the properties setter?
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