I have a generic method with this signature:
private void MyGenericMethod<T>(T arg) where T : class
{}
If I pass, say, an integer to this method, I get an ArgumentException that the passed value does not match the restriction. This is great, but how can I predetermine that what I am passing will match the “class” constraint so that the exception is not thrown?
The compiler will already do that for you – you should actually see:
at compile-time.
The tricky scenarios are:
where T : classa lot. Sometimes it is better to use runtime validation againstTMakeGenericMethod, etc) – again, just check at runtimeAlso, note that
where T : classdoesn’t actually meanTis a class – it means it is a reference-type, which can include interfaces and delegates. Likewise,where T : structdoesn’t actually meanTis astruct– it means it is a struct that is notNullable<>.