Search code examples
c#.netgeneric-constraints

Where constraint for simple types and string


I have a generic method that I would like to put a constraint on.

public T MyMethod<T>(object obj) where T : ???

The constraint is all simple types int, bool etc but I also need to allow string. I there a way of constraining this group?


Solution

  • There's nothing matching exactly what you want, but IConvertible might do - it contains methods to convert a value to all the 'core' types, including string, and is implemented by all the core types you mention.

    The BCL documentation recommends that you don't use this type directly, but instead use Convert.ChangeType or one of the Convert.ToXXX methods as required.