0

I have this code snippet:

foreach (var item in allClassesINeedList)
{
   var genericMethod = temp.GetType().GetMethod("GenerateDocument").MakeGenericMethod(typeof(item));
   genericMethod.Invoke(temp, new object[] { item });
}

This throws an error:

"The type or namespace name 'item' could not be found (are you missing a using directive or an assembly reference?)"

My aim is to execute for every object in allClassesINeedList(its a List<object>) my generic method GenerateSingleDocument with every object in that list.

What did I do wrong ?

2 Answers 2

3

You can Replace typeof(item) with item.GetType()

Sign up to request clarification or add additional context in comments.

1 Comment

To expand - typeof only works on a type known the compiler at compile-time, e.g. typeof(IDisposable). To find the type of an object, use GetType().
1

Do you need to use reflection? If you have control of the classes that you are iterating over, it would be better to create an interface. Reflection is slow and should be avoided where possible.

public interface IDocumentCreator
{
    void GenerateDocument();
}

Add this interface to your classes:

public class YourClass : IDocumentCreator
{
    // ...

    public void GenerateDocument()
    {
        // ...
    }
}

And then make a List<IDocumentCreator> instead of List<object>. You can then call the method in the normal way:

List<IDocumentCreator> allClassesINeedList = ...
foreach(IDocumentCreator item in allClassesINeedList)
{
    item.GenerateDocument();
}

1 Comment

I like your approach, but in my case I have to use relfection, but thxs :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.