Reputation: 431
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
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