Search code examples
c#genericsprimitive-typestype-constraints

Can I define a method that only accepts primitive types?


I want to create a constructor that only accepts primitive types, how can I do this?

Like this example:

public Test(PrimitiveType type)
{

}

I need do it in a constructor and it's optional, so I want to create a parameterless constructor and a constructor with the parameter.


Solution

  • There is no way to do it with a single overload¹ (but you could write overloads for each primitive type, of course). You can make it accept only value types, but then it will accept any struct, not just primitive types.


    ¹ well, it's not possible to enforce it at compile time, but you can check the type at runtime and throw an exception of course...