I created an Class which is only able to handle primitive (or ICloneable) Types
I want to know if it's possible to say something like:
public myobject(primitiv original){...}
or do I really need to create a constructor for each primitive type like:
public myobject(int original){...}
public myobject(bool original){...}
...
What I am trying to achieve is to create an object with 3 public properties Value, Original and IsDirty.
The Value will be an deep Clone of Original so the Original needs to be primitve or ICloneable
Primitive types in C# are defined as structs (implemented generally as ValueType
in the .NET CLR). I believe you have two options:
where T : struct
(with T
being the type parameter). This will catch all structs, not just the primitive types, but I think that's the best you can hope for without manual checking and with compile-time checking. You can mix this constraint with other ones, of course.And you can combine the two options above to have some of the checking be done at compile-time and some of it be done at run-time.
If you want to do that to force whomever is using your API to use such types (through compile time errors should they use the wrong types), I'm afraid it can't be done.
You could, however, receive an object
in the constructor, evaluate its type, and throw an ArgumentException
in case the parameter is neither one of the "primitive" types nor implements ICloneable
.
Edit: This might be useful. You can determine whether a variable belongs to a primitive type with the following code:
Type t = foo.GetType();
t.IsPrimitive; // so you don't have to do an evaluation for each primitive type.
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