Boris Callens
Boris Callens

Reputation: 93387

Checking if any property has been assigned a value

I have a type SearchBag that holds a bunch of strings and nullable integers to use for passing on search values. I need a way to check if the search bag contains any values.

I'm currently trying to do it like this:

    public bool HasValues()
    {
        return GetType().GetProperties().Any(p => p.GetValue(this, null) != null);
    }

But was wondering if there's a better way.

Upvotes: 5

Views: 3231

Answers (2)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68737

You could use Post Sharp to intercept the request to change a property value. You could have all search classes inherit from a common class with a List<string>. Then create an aspect attribute to add a property name to that dictionary whenever the value changes. The following is just a sample, and has bugs:

[Serializable]
public class PropertyChangeAwareAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {
        if (eventArgs.Method.Name.StartsWith("set_")) 
            ((SearchBagBase)eventArgs.Instance).PropertiesChanged.Add(eventArgs.Method.Name);
        base.OnEntry(eventArgs);
    }
}


abstract class SearchBagBase
{
    public List<string> PropertiesChanged = new List<String>();
}

[PropertyChangeAware]
class RegularSearch : SearchBagBase
{
    public String Key { get; set; }
}

with usage:

RegularSearch regularSearch = new RegularSearch();
regularSearch.Key = "toys";
regularSearch.PropertiesChanged.ForEach(Console.WriteLine);

Upvotes: 1

SLaks
SLaks

Reputation: 888167

Without modifying the SearchBag type, there isn't a better way.

EDIT: You could change the type to set a boolean flag in every property setter, then check the flag instead of using Reflection.

Upvotes: 4

Related Questions