No conversion of boxing or type parameters for a general type parameter

I have the following helper method:

public static T CreateRequest<T>()
    where T : Request, new()
{
    T request = new T();
    // ...
    // Assign default values, etc.
    // ...
    return request;
}

I want to use this method from inside another method in another helper:

public T Map<F, T>(F value, T toValue)
    where T : new()
    where F : new()
{
    if (typeof(T).BaseType.FullName == "MyNamespace.Request")
    {
        toValue = MyExtensions.CreateRequest<T>();
    }
    else
    {
        toValue = new T();
    }
}

But then I get the error:

Type "T" cannot be used as a parameter of type "T" in the generic type or method "MyExtensions.CreateRequest ()". There is no box conversion or type parameter conversion from 'T' to 'MyNamespace.Request'.

Is there a way to apply type “T” so that CreateRequest uses it without problems?

EDIT:

I know I can do two things:

  • relax restrictions on CreateRequest or
  • tighten the contours in the map.

, CreateRequest Request, , ( Request) Map.

+5
2

CreateRequest.

public static T CreateRequest<T>()
    where T : new()
{
    if(!typeof(Request).IsAssignableFrom(typeof(T)))
        throw new ArgumentException();

    var result = new T();
    Request request = (Request)(object)result;
   // ...
   // Assign default values, etc.
   // ...
   return result ;
}

, .

, CreateRequest , .

public static object CreateRequest(Type requestType)
 {
    if(!typeof(Request).IsAssignableFrom(requestType))
        throw new ArgumentException();

    var result = Activator.CreateInstance(requestType);
    Request request = (Request)result;
   // ...
   // Assign default values, etc.
   // ...
   return result ;
}
+4

, T Request CreateRequest; , Map . Map :

public T Map<F, T>(F value, T toValue)
where T : Request, new()
where F : new()
+3
source

All Articles