Tuesday, September 16, 2014

How to include value types AND strings in generic constraint.

I'm very like to use generics in the code. Usually generic implementation is working smoothly but exists one small problem with generic value types: cannot use string typed value because System.String is a class.

  1. Foo<string>("abc");



  1. private void Foo(T value) where T : struct
  2. {
  3. //...
  4. }
 
The simple solution is creating overwrite method:

  1. private void Foo(T value) where T : string
  2. {
  3. //...
  4. }

Nice, but not perfect. The beautiful idea was offered by KeithS instead to restrict a value to struct change it to IConvertible. Next types implemented an interface IConvertible but now String can be included in the constraint:
Boolean   
Byte   
Char   
DateTime
Decimal   
Double   
Int16   
Int32   
Int64   
SByte   
Single   
String   
Type   
UInt16   
UInt32   
UInt64 


Final:

  1. private void Foo(T value) where T : IConvertible
  2. {
  3. //...
  4. }