Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5534

Generic arguments

I Have four EF classes with a similar structure and a Generic Class that holds EF structure and some other props and methods, and want to write a generic method cast generic to the desired EF.

private List<T> CastGenericToEF<T>(List<GenericClass> GenericList)
{
    List<T> Target = new List<T>();
    foreach (GenericClass I in GenericList)
    {
        //How can I do to create an Instance of T?
        ..... 
        // Some proccess here 
    }
    return Target;
}

My question: How can I do to create a new instance of T type or get the type of T

Upvotes: 1

Views: 81

Answers (2)

MichaC
MichaC

Reputation: 13380

You have to define that T can have new()

private List<T> CastGenericToEF<T>(List<GenericClass> GenericList) where T: new()
{
    List<T> Target = new List<T>();
    foreach (var generic in GenericList)
    {
        //How can I do to create an Instance of T?
        var tInstance = new T();
        // Some proccess here 
        var typeOf = typeof(T);

    }
    return Target;
}

To access properties/methods of T you'll have to specify it's type in some way. Without a specification, T can be just anything...

the following example defines an Interface somewhere and then specifies that T must actually implement that interface. If you do so

    interface IGenericClass
    {
        void SomeMethod();
    }

you can access properties or methods defined by the interface

    private List<T> CastGenericToEF<T>(List<GenericClass> GenericList) where T : IGenericClass, new()
    {
        List<T> Target = new List<T>();
        foreach (var generic in GenericList)
        {
            //How can I do to create an Instance of T?
            var tInstance = new T();
            tInstance.SomeMethod();
            // Some proccess here 
            var typeOf = typeof(T);

        }
        return Target;
    }

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292435

You need to add a constraint on T:

private List<T> CastGenericToEF<T>(List<GenericClass> GenericList) where T : new()

You can then create an instance of T with new T()

To get the type of T, just use typeof(T)

Upvotes: 2

Related Questions