McArthey McArthey - 2 months ago 10
C# Question

Call object method of generic

I have a method that is passing in a object as a generic. Note that these objects do not derive from the same class. I have a function that I would like to call regardless of the type but am not able to call because it cannot determine the type.

'T' does not contain a definition for 'Validate'


And the code

public void VerifyInput<T>(T obj)
{
((T)obj).Validate();
}


This is being used to validate user data passed in. Each of the classes are responsible for setting their own validation but they are not necessarily related in any way.
I have simplified this but the basic question remains. How can I cast the type of a generic to call an object method?

Answer

Note that these objects do not derive from the same class. I have a function that I would like to call regardless of the type but am not able to call because it cannot determine the type.

This is where you should be using an interface.

public interface IValidatable {
  void Validate();
}

And on your method

public void VerifyInput<T>(T obj) where T : IValidatable
{ 
  obj.Validate();
}

Doing this will ensure that the passed in type conforms to the interface contract but not restrict it to a specific type definition.