简体   繁体   中英

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
    } 
    else 
    { 
        // it's not do stuff with param
    }
}

The user can enter either a integer or a string into a text box.

Seems simple to me then. You get the input from the textbox through the Text property which is always a string. So you need to check if the input can be parsed to an integer using TryParse. Personally I don't see why you need overloaded methods. Are the methods the same except for the type of the param? If not I would not choose to overload but just different ones with clear naming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM