Eli
Eli

Reputation: 4926

Use instance's method in generic method

My code goes like this:

public T ReadState<T>(string file_path)
{
    string file_content = ...read file..from file_path...        
    T state = ...xml deserialize...
    state.SetSomething(); //  <--the problem is here <--
    return state;
}

I want to use this generic method on a various object types. Of course, they all implementing the SetSomething() method

Currently, the compiler complains:

'T' does not contain a definition for SetSomething()...

TIA!

Upvotes: 0

Views: 59

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500785

Of course, they all implementing the SetSomething() method

Then you should tell the compiler that:

  • Create an interface with the SetSomething() method
  • Make all the relevant types implement the interface
  • Constrain T to implement that interface:

    public T ReadState<T>(string file_path) where T : IYourNewInterface
    

If you can't make the types all implement an interface, the simplest solution is probably to use dynamic typing:

((dynamic) state).SetSomething();

The interface solution is far cleaner though, where feasible.

Upvotes: 5

Related Questions