views:

59

answers:

2

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.

+3  A: 

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.

SLaks
Nothing keeps me from changing it..
borisCallens
@boris: See my edit.
SLaks
Thx. Yes thought about that but that would require me to convert all auto properties to value backed properties and implement the logic in each setter. It's an option, but I think the reflection cost is not worth it. Thanks for the suggestion.
borisCallens
+1  A: 

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);
Yuriy Faktorovich
As I'm unfamiliar with PostSharp I had a quick glance at Post Sharp. Looking forward to your example
borisCallens
Not sure the reflector overhead in my particular case is worth the trouble, but it seems like an interesting library on a whole. I will keep this in mind for later use. Thx :)
borisCallens
@boris I created a solution using this library to tell if a piece of data from the database was dirty or not. It ended up being reusable in many other situations.
Yuriy Faktorovich