Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass generic type to generic method?

I want to invoke a method accepting T type object. In my custom method I'm receiving T type. How can I pass my T type to the method which is already receiving a T type? Can it be invoked via reflection?

Below is my method:

public IEnumerable<T> Method2<T>(string fileSrc, char sep)
{
    // Using LinqToCsv lib  
    IEnumerable<T> list;

    CsvFileDescription inputFileDescription = new CsvFileDescription
    {
        SeparatorChar = sep,//specify the separator line  
        FirstLineHasColumnNames = true //Header is in the first line  
    };
    CsvContext csvContext = new CsvContext();
    list = csvContext.Read<T>(fileSrc, inputFileDescription);

    // Data is now available via variable list.  
    return list;
}

In the above method csvContext.Read<T>(fileSrc, inputFileDescription); is declared as

public IEnumerable<T> Read<T>(string fileName, CsvFileDescription fileDescription) 
    where T : class, new();

I will be grateful for the help.

like image 646
Mubsher Mughal Avatar asked Jan 02 '26 03:01

Mubsher Mughal


1 Answers

When you call a generic method you need to make sure that the type parameter matches the same generic constraints.

So you need to change your method declaration to

public IEnumerable<T> Method2<T>(string fileSrc, char sep) where T : class, new()

in order to invoke the the Read<T>() method which requires its T type argument to match these constraints.

like image 86
Martin Ullrich Avatar answered Jan 03 '26 16:01

Martin Ullrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!