Reading a property of a concrete class in a generic method that does not get an instance of the generic type

Suppose I have a generic method that is made generic just to return the correct type, so upstream callers don't need to return return values.

public T Add<T>(string name, string details, ...)
    where T: BaseClass
{
    // somehow get correct ObjectType
    ObjectType type = ??????;
    T result = Repo.Add<T>(type, name, details, ...);
    ...
    return result;
}

      

Problem

The problem with this generic method is that I am not getting an instance of a specific class represented with a generic type. This means that the callers of this method must explicitly provide a generic type, since type inference cannot be performed.

public abstract class BaseClass
{
    public abstract ObjectType ActualType { get; }

    ...
}

      

Implemented child classes define this property as a constant constant

public class ConcreteClass: BaseClass
{
    public override ObjectType ActualType
    {
        get { return ObjectType.SomeType; }
    }

    ...
}

      

Question

Based on a call to a common method

var result = Add<ConcreteClass>("title", "details");

      

how can i get the value ActualType

in my method Add<T>

? I also tried to add a new()

generic type constraint , but that won't compile as mine is BaseClass

abstract, so I can't call

new T();

      

in my method to get this value ActualType

.

+3


source to share


1 answer


You need to apply constraint new()

to your method Add

like this:

public T Add<T>(string name, string details)
    where T: BaseClass, new()
{
    T result = new T();
    //snip  
    return result;
}

public abstract class BaseClass { /* snip */ }

public class ConcreteClass: BaseClass { /* snip */ }

      

This means this code will work:

var thing = Add<ConcreteClass>("Fred", "Lives in France");

      



According to the MSDN documentation in the new constraint :

The new constraint specifies that any type argument in a generic class declaration must have a public, parameterless constructor. Use a new constraint, the type cannot be abstract .

This refers to the type passed in, not another constraint in your method.

0


source







All Articles