WiiMaxx
WiiMaxx

Reputation: 5420

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

Upvotes: 5

Views: 438

Answers (4)

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

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.

Upvotes: 6

Juan Ayala
Juan Ayala

Reputation: 3518

How about generics instead of reflection?

public class MyObject<T>
    where T: IComparable
{
    public MyObject(T original)
    {
        // do runtime check
    }
}


var c1 = new MyObject<int>(1);
// or
var c2 = new MyObject<Int32>(2);

Upvotes: -2

Corneliu
Corneliu

Reputation: 2942

It is not exactly what you asked, but you can have 2 constructors, one for structs and one for ICloneable:

 public myobject(System.ValueType original){...}
 public myobject(ICloneable original){...}

Upvotes: 2

Geeky Guy
Geeky Guy

Reputation: 9399

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.

Upvotes: 6

Related Questions