1

I want to create a class like this

public class MyClass<T> where T:int || T:decimal || T:double || T:float ||T:long
{
public T DoSomething()
{}
}

Is it possible to do this in C#?

Nicolas De Irisarri
  • 1,077
  • 1
  • 14
  • 27

1 Answers1

3

You can't do this, but you can use struct constraint which means that type argument must be a value type:

public class MyClass<T> where T: struct
{
  public T DoSomething()
  {  
    // your code
  }
}

Take a look at Constraints on Type Parameters

Zbigniew
  • 27,184
  • 6
  • 59
  • 66
  • The thing is I don't want to allow MyClass since I am performing numeric operations... – Nicolas De Irisarri Aug 22 '12 at 16:33
  • 1
    It seems that this is similar to [Generic constraint to match numeric types](http://stackoverflow.com/questions/3329576/generic-constraint-to-match-numeric-types) – Zbigniew Aug 22 '12 at 16:39
  • Marc gravell's article referred in the question you suggested did it. Thanks! here's the url. http://yoda.arachsys.com/csharp/genericoperators.html – Nicolas De Irisarri Aug 23 '12 at 22:24