Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# optional properties in C# 3.0 (2009)

Tags:

c#

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.

like image 967
Wei Ma Avatar asked Nov 09 '09 08:11

Wei Ma


2 Answers

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.

like image 76
Elisha Avatar answered Nov 27 '22 09:11

Elisha


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?

like image 38
Stuart Grassie Avatar answered Nov 27 '22 10:11

Stuart Grassie