Is there a way to check the properties of a class for a specific value in C #

I have a License class. There are 50 boolean properties and some timestamp properties. I want to inform the user that all these 50 properties are false.

One way is to use 50 if and if conditions. Another way is reflection, which seems overkill for this thing. Please suggest another way. I am using .Net framework 3.5

+2


source to share


3 answers


You could do it with reflection:

var values = from prop in typeof(License).GetProperties()
             where prop.PropertyType == typeof(bool)
             select (bool) prop.GetValue(instance, null);

if (!values.Any(x => x))
{
    // Nope, everything false
}

      



I'm not sure what you want to do with the timestamp parameters ...

+3


source


Can you change the construction of the class?

In this case, if the booleans are related in some way, you can use the following:



And then just use a loop for

or to check the values foreach

.

Besides, meditation is your friend.

+1


source


You should take a look at Indexed Property . You can encapsulate the validation in the read-only property of the license:

private List<Boolean> props;

public bool IsExpired
{
    get { return !props.Any(p => p); }
}

      

0


source







All Articles