I'm having a bit of trouble working out how to decide the type of a generic at runtime.

For example what I would like to do is decide the type of a generic class depending on user input. The problem being the generic variable that needs to be assigned is a class property and I can't find a way of just declaring the property in a way like : MyClass<> _class; then doing a new assignment in a switch based on user input.

Anyone know a way to do this?

9 Years
Discussion Span
Last Post by sknake

I'm not sure I understand what you are asking but you can do many things.

private void button4_Click(object sender, EventArgs e)
      object o = new string('x', 5);
      if (o is int)
        MessageBox.Show("It is an integer..");
      else if (o is string)
        MessageBox.Show("It is a string");
        MessageBox.Show(string.Format("Unknown type: {0}", o.GetType().ToString()));

By calling .GetType() you can take a look at the class, the base class, and reflect out interfaces etc.


not really what i meant but thx for the reply, i got what I wanted by using an object type then casting when I needed to.



Sounds good

Please mark this thread as solved since you have found a solution to your original question and good luck!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.