user1174834
user1174834

Reputation: 239

TryParse and Variables

I am just learning C# and I am trying to learn more about TryParse and how it relates to and interacts with established variables. In the following example I'm simply confirming whether the values in a text box are indeed decimals and that they fall within a given range. Otherwise, I call the BadInput() method which displays an error message.

private void VerifyNums()
    {
        if (decimal.TryParse(Val1Box.Text, out Val1)&& (val1<=100) && (Val1>=0))
        {
            if (decimal.TryParse(Val2Box.Text, out Val2) && (Val2 <=100) && (Val2 >=0))
            {
                if (decimal.TryParse(Val3.Text, out Val3) && (Val3 <100) && (Val3 >=0))
                {
                    GoodInput();
                }
                else
                {
                    BadInput();
                }
            }
            else
            {
                BadInput();
            }
        }
        else
        {
            BadInput();
        }
    }

First Question: What does OUT do in a TryParse? Does it set Val1 equal to the contents of the text box?

Second Question: Is it possible to Parse and check the variables Val1, Val2 and Val3 and then be able to use them as input or arguments in other methods? If so, how is that done? I have read a lot about OUT and REF I just don't understand how they work.

Upvotes: 0

Views: 2983

Answers (4)

Demian
Demian

Reputation: 372

1) C# Passes parameters by value by default. Out allows the passing of the parameter by reference instead of by value. In practical terms, it means that the value you pass to the function can be modified inside it.

To answer your question:

If TryParse returns true: then the value of the textbox was sucesfully parsed and assigned to Val1. If it returns false: then the conversion failed and the value of Val1 (or Val2, or whatever you are trying to parse) will be zero.

2) Out simply means that their reference was passed to a funcction (and that their value was likely modified). Other than that, you can treat them as ordinary variables (because that's exactly what they are).

For example, doing something like this is perfectly valid:

if (decimal.TryParse(Val1Box.Text, out Val1)&& (Val1<=100) && (Val1>=0))
{
   GoodInput(Val1);
}

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23132

The out keyword [MSDN] in C# indicates that the method (e.g. TryParse) must assign a value to that variable before the method returns. This provides you with a construct that is effectively giving you two or more return values from a single method. (Use sparingly.)

You see this pattern a lot in C#, both in framework and user code, with operations that would otherwise need to throw an exception if they fail. If you passed "Gonzo" into the decimal.Parse method, for example, there's no value that it could meaningfully return to you that would indicate that the operation failed, so it must throw an exception. By implementing the TryParse pattern you get to return a Boolean value indicating if the parse operation succeeded or not, and if it did the out parameter would have the result of that operation. In the case of the operation failing, the out parameter would still be assigned a value, but you couldn't rely on that value to be anything meaningful.

So, to answer your question 1: Yes, decimal.TryParse sets the value of the out parameter to the parsed text from the textbox, but only if that text is a valid decimal, in which case the method also returns true. If the text doesn't represent a valid decimal, the method returns false and sets the value of the out parameter to zero.

As for question 2: Certainly it is possible to use the out variables once TryParse is complete. Like so:

decimal Val1;
if (decimal.TryParse(Val1Box.Text, out Val1) && (Val1 <= 100) && (Val1 >= 0)
{
    // Continue to use the variable Var1 as a valid decimal, 
    // because that's what it's guaranteed to be. 
    //
    // You're even able to use it within the conditional expression 
    // of the if statement as above.
}

Upvotes: 0

D Stanley
D Stanley

Reputation: 152511

What does OUT do in a TryParse? Does it set Val1 equal to the contents of the text box?

It sets Val to the decimal that is represented by the string passed into the first parameter (in your case, a TextBox value).

out means that an output of that function will be stored in that variable. It's an alternative to a return value like int.Parse uses:

decimal val = decimal.Parse("123");

Since a function can only return one value, MS chose to return a bool and use an out parameter for the parse result rather than returning a composite structure or using the bool as the out param:

bool isSussessful;
decimal val = int.TryParse("123", out isSuccessful);

but that would have prevented inlining the parse into an if statement.

Your error is a result of not declaring Val1 first:

    decimal Val1;
    if (decimal.TryParse(Val1Box.Text, out Val1)&& (Val1<=100) && (Val1>=0))
    {
        decimal Val2;
        if (decimal.TryParse(Val2Box.Text, out Val2) && (Val2 <=100) && (Val2 >=0))
        {

Is it possible to Parse and check the variables Val1, Val2 and Val3 and then be able to use them as input or arguments in other methods

Absolutely - just like you would any other variables. out only makes a difference when passing the variable into a function (with ref the variable must be initialized, with out it does not).

Upvotes: 4

Steve
Steve

Reputation: 216263

The out keyword that prefix a parameter's method means that the called method SHOULD initialize the variable in a way or another (for example invalid values in the textbox result in the valX parameter intialized with zero). The variable of course is available in the calling method after the TryParse and thus can be used as a parameter for other methods or functions

bool v1Good = decimal.TryParse(Val1Box.Text, out Val1);
bool v2Good = decimal.TryParse(Val2Box.Text, out Val2);
bool v3Good = decimal.TryParse(Val3.Text, out Val3);

if(v1Good && v2Good && v3Good)
{
   if(val1 >=0 && val1 <= 100 && val2 >= 0 && val2 <=100 && val3 >= 0 && val3 <= 100)
   {
       // You could pass them to the GoodInput method
       GoodInput(val1, val2, val3);
   }
   else
       BadInput();
}
else
    BadInput();

Upvotes: 1

Related Questions