Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors on applying Generics methods

Tags:

c#

generics

With reference to my previous question, I have tuned my code to use Generics like

FileHelperEngine engine;
public DateTime ExportResultsToCsv<T>(string filePath, string HeaderLine, List<T> data)   
{
    engine = new FileHelperEngine(typeof(T)) { HeaderText = HeaderLine };
    engine.WriteFile(filePath, data);
    return DateTime.Now;   
}

However when I tried to integrate it in my code, I'm facing the following 2 errors:

Error 1 The best overloaded method match for 'FileHelpers.FileHelperEngine<object>.WriteFile(string, System.Collections.Generic.IEnumerable<object>)' has some invalid arguments

Error 2 Argument 2: cannot convert from 'System.Collections.Generic.List<T>' to 'System.Collections.Generic.IEnumerable<object>'

I couldn't get what the error is about. Can someone help on this.

Error line :

engine.WriteFile(filePath, data);

Updates1:

I'm using FileHelper.dll for Csv file conversion and FileHelperEngine is class belongs to that dll.

Updates2: As @sza suggested, I changed and following is the screenshot of my error

enter image description here Thanks in advance.

like image 454
Praveen Avatar asked Mar 22 '23 14:03

Praveen


2 Answers

Here is why. Let's take a look at the source code

        /// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile/*'/>
#if ! GENERICS
        public void WriteFile(string fileName, IEnumerable records)
#else
        public void WriteFile(string fileName, IEnumerable<T> records)
#endif
        {
            WriteFile(fileName, records, -1);
        }

Since you are not using generic type of FileHelperEngine (the generic way is FileHelperEngine<T>), you can see the method takes the 2nd parameter as IEnumerable, which is not the generic IEnumerable<T> but a simple iteration over a non-generic collection.

So I believe you can do the following to make your code work:

engine.WriteFile(filePath, (IEnumerable)data);

or

engine.WriteFile(filePath, data as IEnumerable);

or

engine.WriteFile(filePath, data.Cast<Object>());

Hope it helps.

like image 165
zs2020 Avatar answered Mar 25 '23 03:03

zs2020


I fixed the generic tags in your question, and it now becomes apparent that you're trying to call WriteFile with an invalid type. Try casting your objects to, well, Object.

engine.WriteFile(filePath, data.Cast<Object>());

The problem occurs because List<T> implements IEnumerable<T>, not IEnumerable<Object> which the method expects.

like image 22
sisve Avatar answered Mar 25 '23 03:03

sisve