.Net Generics - Wrapper
Have you ever needed a wrapper object that can expose the properties for any object it encompasses?
I frequently do, as when loading a list of entities from the database I often want to send a SearchFilterCriteria object down the call stack for filtering. Nine times out of ten this ends up having the same properties as my Entity. i don't just want to pass an Entity down the call stack and use that as the filter as that feels a bit wrong. What I want is an object that I can wrap around any entity and expose all of the entity properties.
Finally I have found a way to do this and that is with generics. I'd like to share with you what I cam up with. below is the class which will wrap any entity type and expose it as a property.
/// Encapsualtes search criteria.
/// <typeparam name="T"></typeparam>
public class SearchFilterCriteria<T> where T : new()
private T _internalCriteria = default(T);
/// Gets the criteria.
public T Criteria
if (this._internalCriteria == null || this._internalCriteria.Equals(default(T)))
this._internalCriteria = new T();
And here an example of using the beast for my event object that has many properties but includes Active and Name properties.
public static SearchFilterCriteria<Event> CreateEventSearchFilterCriteria()
SearchFilterCriteria<Event> s = new SearchFilterCriteria<Event>();
// Set the default values...
s.Criteria.Active = true;
s.Criteria.Name = "Easter";
All of the properties of the Entity are exposed through the Wrapper's Criteria property. If I could just find out how to pass a method parameter as a typeparam I would be really happy. Then I could have a generic factory method that could create a SearchFilterCriteria for any Type, rather than having to have a CreateFooSearchFilterCriteria() and a CreateBarSearchFilterCriteria() method for each type.
Anyway, I hope that may be of some use to you in some future project.