Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell a constructor it should only use primitive types

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

like image 773
WiiMaxx Avatar asked Jun 17 '13 13:06

WiiMaxx


2 Answers

Primitive types in C# are defined as structs (implemented generally as ValueType in the .NET CLR). I believe you have two options:

  1. As has been said already: Receive any type, check it against every acceptable type, throw an exception if it doesn't match.
  2. Make your class generic, make the constructor generic with a constraint of 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.

like image 98
Theodoros Chatzigiannakis Avatar answered Sep 28 '22 01:09

Theodoros Chatzigiannakis


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.
like image 42
Geeky Guy Avatar answered Sep 28 '22 01:09

Geeky Guy