realist
realist

Reputation: 2375

Sending empty class to generic class as default parameter in C#

I have a QueryFilter<TSearchFilter> class (see below). And I created a QueryFilter class that inherits from this class. I'm currently using the QueryFilter without specifying the type, like this:

var queryFilter = new QueryFilter();

To do this, I created a fake EmptySearchFilter class for achieving this. This works perfectly; no problem.

public class QueryFilter<TSearchFilter> where TSearchFilter : class
{
    public QueryFilter()
    {
        SearchFilter = (TSearchFilter)Activator.CreateInstance(typeof(TSearchFilter));
    }
    public string SortBy { get; set; }
    public int PageFirstIndex { get; set; }
    public byte PageSize { get; set; }
    public TSearchFilter SearchFilter { get; set; }
}

public class QueryFilter : QueryFilter<EmptySearchFilter> { }

public class EmptySearchFilter { }

But, I think that there's probably a way to avoid using this fake class (EmptySearchFilter) by doing something like:

public class QueryFilter : QueryFilter<typeof(Class)>{ }

Is there a way to do this?

Upvotes: 0

Views: 77

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

You can reverse the inheritance chain like this:

public class QueryFilter 
{ 
    public string SortBy { get; set; }
    public int PageFirstIndex { get; set; }
    public byte PageSize { get; set; }
}

public class QueryFilter<TSearchFilter> : QueryFilter 
    where TSearchFilter : class, new() 
{
    public QueryFilter()
    {
        SearchFilter = new TSearchFilter();
    }
    public TSearchFilter SearchFilter { get; set; }
}

This way, the QueryFilter does not need to use a fake class.

Also, I've added a new() constraint to get rid of the Activator.CreateInstance call.

Upvotes: 2

Related Questions