dotnetnoob
dotnetnoob

Reputation: 11330

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?

Upvotes: 1

Views: 144

Answers (2)

thecoop
thecoop

Reputation: 46098

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.

Upvotes: 1

Gent
Gent

Reputation: 2685

I believe structure will give you all of the types you are looking for sans string. It will also allow any that have been defined though, which is a problem you will have with any solution for this.

Honestly though this seems like its probably over engineering. You should consider your requirements again and see if this is actually needed.

Upvotes: 0

Related Questions