Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 596
Only a Curious Mind Avatar asked Jun 11 '14 18:06

Only a Curious Mind


2 Answers

Depending upon what you want to achieve, you might want to look at so-called "convertible types", e.g. the types that implement IConvertible interface, those are the following:

  • Boolean,
  • SByte,
  • Byte,
  • Int16,
  • UInt16,
  • Int32,
  • UInt32,
  • Int64,
  • UInt64,
  • Single,
  • Double,
  • Decimal,
  • DateTime,
  • Char, and
  • String.

So, as you see, this covers pretty much of what you'd like to achieve with primitive types.

So, by writing the method like that

public void Test(IConvertible primitive)
{
   if (primitive is Double) ....
   if (primitive is String) ....
}

you will confine your input types to the following ones (no structs etc).

Alternatively, you can also implement it as a generic method:

public void Test<T>(T primitive) where T : IConvertible
{
   if (primitive is Double) ....
   if (primitive is String) ....
}

Since you put this constrain, you can always convert your type to one, like:

public void Test<T>(T primitive) where T : IConvertible
{
   var myval = Convert.ToDecimal(primitive);
   ....
}
like image 72
Alexander Galkin Avatar answered Sep 18 '22 02:09

Alexander Galkin


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...

like image 31
Thomas Levesque Avatar answered Sep 21 '22 02:09

Thomas Levesque