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.
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);
....
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With