DummyBeginner
DummyBeginner

Reputation: 431

Detect the type of parameter passed in class constructor

I want the constructor of a class to be able to pass two types of parameters, then inside the method do some stuff based on the type of the parameter. the types would be double and String[]. the class and its constructor is something similar to:

public class MyClass
{
    public MyClass (Type par /* the syntax here is my issue */ )
    {
        if (Type.GetType(par) == String[])
        {  
            /// Do the stuff
        }

        if (Type.GetType(par) == double)
        {  
            /// Do another stuff 
        }
}

and the class would be instantiated on another class this way:

double d;
String[] a;

new MyClass(d);    /// or new MyClass(a);

Upvotes: 0

Views: 599

Answers (2)

BugFinder
BugFinder

Reputation: 17868

You could use the following - but I wouldn't recommend it. Separate constructors (as shown in the other answer ) would be simpler and much better from type safety point of view.

public MyClass(object par)
{

    if (par.GetType() == typeof(double))
    {
        // do double stuff
    }
    if (par.GetType() == typeof(string))
    {
        // do string stuff
    }
    else
    {
       // unexpected - fail somehow, i.e. throw ...
    }
}

Upvotes: 1

litelite
litelite

Reputation: 2849

The simplest way would be to create two constructors. One for each type.

public class MyClass
{
   public MyClass (Double d)
   {
        //stuff
   }

   public MyClass(String[] s)
   {
       //other stuff
   }
}

Also, i recommend you read this article

Upvotes: 5

Related Questions