Maryam Taghavi
Maryam Taghavi

Reputation: 37

error: Use of unassigned local variable

I have this method:

public static void Add(int _Serial, string _Name, long? _number1, long? _number2)
{
    // ...
}

and use this code for send date to method:

long? _num1;
long? _num2;
if (txtNumber1.Text != null && txtNumber1.Text != "")
{
    _num1= long.Parse(txtNumber1.Text);
}
if (txtNumber2.Text != null && txtNumber2.Text != "")
{
    _num2= long.Parse(txtNumber2.Text);
}
Add(22, "Kati", _num1, _num2)

but Error _num1 & _num2 in Add(...).

Error:

Use of unassigned local variable '_num1'

Use of unassigned local variable '_num2'

Upvotes: 1

Views: 1345

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

Yes, you must initialize local variables before usage. But in this case you can remove those variables (see refactoring below).

There is nice method String.IsNullOrEmpty in the box. You can use it to verify if some string has value "" or null. Also, I'd moved parsing nullables to separate method:

private long? ParseNullableLong(string s)
{
    return String.IsNullOrEmpty(s) ? null : (long?)Int64.Parse(s);
}

Then declare two properties for retrieving values from UI (of course, consider better names):

private long? Number1
{
    get { return ParseNullableLong(txtNumber1.Text); }
}

private long? Number2
{
    get { return ParseNullableLong(txtNumber2.Text); }
}

And now all your code will look like:

Add(22, "Kati", Number1, Number2);

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112682

Kendall Frey answers your question. I just would like to suggest you another approach for parsing numbers here.

long? _num1 = null;
long result;

if (Int64.TryParse(txtNumber1.Text, out result)) {
    _num1 = result;
}

This is easier an safer, as TryParse will not throw an exception, even if the text is null, empty or not a number.

Upvotes: 0

Kendall Frey
Kendall Frey

Reputation: 44374

The compiler doesn't know whether those if statements are going to be executed, so it considers the worst case scenario, and realizes that one or both variables may not be initialized before they are used in Add.

The solution is to initialize them at declaration, like this:

long? _num1 = null;
long? _num2 = null;

Upvotes: 5

Related Questions