Jeff Jeff - 1 month ago 6
C# Question

C# variable questions

I am working on a project, in C#, that needs to run a method based off of user input. The user can enter either a integer or a string into a text box. Is it possible to create an undeclared variable and if not, how do I go about using the right method for the user input? I plan on creating two overloaded methods.


You can use object as type for your param and then use .GetType() or is to perform type checking. There are other alternatives like dynamic but it's more common to use dynamic when you need to perform method calls on your object without having to cast it to its actual type

Anyway if you're reading from console, it will always be a string, so you can int.TryParse() on it.

public void DoStuff(string param) 
    int chosen;
    if(int.TryParse(param, out chosen) 
        // is an int do stuff with chosen
        // it's not do stuff with param