Neil Knight
Neil Knight

Reputation: 48537

Extending a method that has a return type

I'm trying to extend a method that already has a return type. For example:

IQueryable<int> GetCategoryIds()

So, I can use this as follows:

IQueryable<int> categories = GetCategoryIds();

And I'm currently doing:

IQueryable<int> categories = GetCategoryIds().Select(c => new Client() { ClientId == c.clientId });

This works, but I don't want to do that Select statement. I'd rather do an extension method that excepts a type so I can use Reflection in the extension method to determine the type etc. and return the results according. The extension method would be something like:

public static IQueryable<T> LovelyExtension(this T objectType, int clientId)

Then I can use this extension like (hopefully):

IQueryable<int> categories = GetCategoryIds().LovelyExtension<int>(1);

Is this possible? When I tried it, I got an error because the GetCategoryIds return type wasn't the same as the extension method. But, this works with the Select statement.

Upvotes: 0

Views: 135

Answers (3)

M Afifi
M Afifi

Reputation: 4795

Change your signature from,

public static IQueryable<T> LovelyExtension(this T objectType, int clientId) 

to

public static T LovelyExtension(this T objectType, int clientId) 

or

public static IQueryable<T> LovelyExtension(this IQuerable<T> objectType, int clientId) 

GetCategoryIds() returns an IQuerable (which is what your passing into LovelyExtension's objectType, your return type based on your original signature becomes IQuerable> which obviously won't match what you're after.

Upvotes: 0

Sean Barlow
Sean Barlow

Reputation: 588

I believe you will need to declare an interface on your client class and add a constratint to your extension method. Take a look at this post generic extension method

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You do not need to write an extension on Type (your example is not doing it either). You need an extension on IQueryable<T>. You can do it like this:

public static IQueryable<T> LovelyExtension<T>(this IQueryable<T> input, int clientId) {
    Type inputType = typeof(T);
    // Here you can use reflection if you need to: inputType corresponds to the type of T
    // Create an instance of IQueryable<T>, and return it to the caller.
}

Upvotes: 2

Related Questions