MissingMethodException calling a method with generic parameter

247 views Asked by At

I have a library containing a class with two methods (and some others that aren't relevant):

public T Foo<T>()
{
    // Real version does some other things, but this is the gist.
    return (T)this.Foo();
}

public object Foo()
{
    // Do stuff and return something.
}

So far so good. This library compiles.

Yet when calling .Foo<string>() I get a MissingMethodException. What could be causing this? Everything compiles fine.

For reference the Foo without the generic is the legacy method, I am introducing the generic version to help with casting etc.

1

There are 1 answers

2
Stephanie On BEST ANSWER

I agree that the MissingMethodException is due to old dlls. However, once you fix that, this still won't work. You can't implicit cast an object to a string. At runtime, your call .Foo<string>() will call (String)Foo(), where Foo is of type Object. This will basically never work unless the T you provide is already object.

Read more about type conversions here, including an explanation of narrowing versus widening casting.

What is it you are trying to do with this piece of code? If you expect to always be using .Foo<string>() or a subset of a few types then you could just define explicit casts for them instead.