Reputation: 4926
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
Reputation: 1500785
Of course, they all implementing the
SetSomething()
method
Then you should tell the compiler that:
SetSomething()
methodConstrain 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