1

Is there a way to specify a data type (specifically: int, text, byte, char) as a parameter? For example: (this doesn't work)

public void myclass(System.Object ChoosenType)
{
    switch (ChoosenType)
        case System.Text:
        case System.Byte:
        case System.Int32:
        case Sustem.Char:
}
UpTide
  • 307
  • 3
  • 13
  • 1
    Sounds like a [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you trying to achieve? Looks like a pretty bad code smell to me. – Pierre-Luc Pineault Aug 22 '15 at 00:30
  • Sorry about the duplicate. I am somewhat new so my vocabulary is lacking. – UpTide Aug 22 '15 at 00:36

2 Answers2

2

You can, by using the Type class. However, you can't use a switch statement since you can't switch on Type objects.

CS0151 A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type

You also need to change your comparison method, as the "type name" of a type is not a Type object. You have to use typeof:

public void someMethod(Type theType)
{
    if (theType == typeof(Int32))
    {
    }
    else if (theType == typeof(Char))
    {
    }
    ...
}

Also note that System.Text is not a type, but a namespace. System.String on the other hand is a type.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

Also worth noting that in addition to using the Type class, you could replace the System.Int32 with it's alias, int. This works because int is really just a "nickname" for the fully qualified System.Int32 class.

ex-

public void myClass(Type x)
{
    if (x == typeof(int))
    {
        Console.WriteLine("int");
    }
    else if (x == typeof(bool))
    {
        Console.WriteLine("bool");
    }
    else if (x == typeof(string))
    {
        Console.WriteLine("string");
    }
    //additional Type tests can go here
    else Console.WriteLine("Invalid type");
}
John Smith
  • 7,243
  • 6
  • 49
  • 61