Chris McGrath
Chris McGrath

Reputation: 1757

Using type of extension parameter to pass as an Generic type parameter

I am attempting to write and extension method that takes the type of a this parameter and passes it along to a generically typed method ie

public TDestination MethodName<TSource, TDestination>(this TSource obj)
{
      return DestinationClass.DestinationMethod<TSource, TDestination>(obj)
}

How can I assume the type of the this parameter as the type of the Destination Method is this possible with defining the TSource when calling the method

Clarification: I want to create a helper method so that i can directly call MethodName from an object and use a prewritten generic method with 2 types so i want to shorten this to a single destination type and have the method assume the type of the object being passed to the extension method

Usage Example: ie AutoMapper extension example

Original Method Call:

  var person = _db.People.Single(q=>q.Id == 5);
  //use automapper directly to map object 
  return Mapper.Map<Person, PersonDisplay>(person);

I want to shorten this down to

  var person = _db.People.Single(q=>q.Id == 5);

  //use extension method to map 
  return person.MapTo<PersonDisplay>()  

Want to shorten this to

Upvotes: 1

Views: 174

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062510

You cannot. Generic parameters must be all explicit or all implicit. You cannot get the compiler to infer one yet supply the other. Consequently you will require a different API. Maybe via an intermediate so you have something like:

obj.Foo().Bar<AnotherType>();

which is possible.

Upvotes: 1

Related Questions