Davut Gürbüz
Davut Gürbüz

Reputation: 5716

Is it possible to pass just one parameter for this generic extension method?

 //In a Static class ,extension implementation
 public static IQueryable<T2> ToDTO<T, T2>(this IQueryable<T> source)
    {
        return source.To<T2>();
    }

//Usage
var result = personType1Queryable.ToDTO< personType1, personType2>();

In above code as you see its an extension. It converts one type to another. So first this referenced object is personType1Queryable typed IQueryable < personType1 > I just want to call this function like this;

personType1Queryable.ToDTO<personType2>();

I just want to pass just destination type. Because this referenced object already passed. But compiler doesn't accept this why? For Where < T > extension in Linq it works. For me why not?

EDIT: I applied Eren's answer. But it seems still something missing.

  //works
    public static IQueryable<T2> ToDTO<T,T2>(this IQueryable<T> source)
    {
        return source.Project().To<T2>();
    }

  //gives object reference error. Shown below!
    public static IQueryable<T> ToDTO<T>(this IQueryable<object> source)
    {
        return source.Project().To<T>();
    }

enter image description here

https://i.sstatic.net/9Yh6H.png

Upvotes: 1

Views: 131

Answers (2)

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

IQueryable<T> is covariant in T, so depending on what you need in the To<T> extension, you might get away with this:

public static IQueryable<T> ToDTO<T>(this IQueryable<object> source)
{
    return source.To<T>();
}

Note that this will only work if the type parameter of the original IQueryable<T> (e.g. personType1) is a reference type. Otherwise, you'll get a compiler error.

Upvotes: 1

Jakub Konecki
Jakub Konecki

Reputation: 46008

Where is defined as

public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )

As you can see it uses only one generic parameter, that's why it 'works' when you provide one. Your method is defined with two parameters.

Upvotes: 0

Related Questions