use of unassigned local variable c что значит
What does «Use of unassigned local variable» mean?
I keep getting this error for annualRate, monthlyCharge, and lateFee.
11 Answers 11
The compiler isn’t smart enough to know that at least one of your if blocks will be executed. Therefore, it doesn’t see that variables like annualRate will be assigned no matter what. Here’s how you can make the compiler understand:
The compiler knows that with an if/else block, one of the blocks is guaranteed to be executed, and therefore if you’re assigning the variable in all of the blocks, it won’t give the compiler error.
By the way, you can also use a switch statement instead of if s to maybe make your code cleaner.
Change your declarations to this:
The error is caused because there is at least one path through your code where these variables end up not getting set to anything.
Because if none of the if statements evaluate to true then the local variable will be unassigned. Throw an else statement in there and assign some values to those variables in case the if statements don’t evaluate to true. Post back here if that doesn’t make the error go away.
Your other option is to initialize the variables to some default value when you declare them at the beginning of your code.
Give them a default value:
Basically, all possible paths don’t initialize these variables.
Use the keyword «default».
Your assignments are all nested within your conditional if blocks which means that there is potential for them to never be assigned.
At the top of your class, initialise them to 0 or some other value
There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.
As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else statement).
I would however like to point out other potential improvements:
After searching around I cant seem to locate why the C# compiler is complaining that the local variable dteDest is unassigned in the line
The error goes away if I replace the line
As far as I can see the code will never reach the comparison line if dteDest is not initialised by the DateTime.TryParse which it is an out parameter for.
Simple Sample Code
Also if I change the line
then the compiler complains that srcDate is not assigned as well.
Additional Info
Even expanding out the logic still gives the same error (use of unassigned local variable)
5 Answers 5
Your replace is incorrect, it should be:
However you should use the return variable of TryParse, which is a bool to see if tryparse worked instead if your booHaveNewDate:
Now you do not have to assign the dates in the beginning.
** You should test this code before using, it is no production code and can contain errors
The compiler is formally correct, the assignment to dteDest (as out parameter) is conditional. In the eyes of the compiler it might not happen. The compiler doesn’t ‘understand’ the logic that follows from TryParse().
Here is a similar situation:
On a side note, it seems slightly more logical to initialize with
it is the same value (DateTime.MinValue) though.
I could be wrong but I don’t think the compiler attempts to dissect your code that extensively when reporting this error. I’m currently trying to find some source to back up my theory. In the mean time, my guess would be that this is a design decision because if it takes a person more than a couple seconds to see that a variable will not be used before being initialized it’s probably a better coding decision to just null initialize it to begin with in order to avoid confusion.
Well I did a bit of looking around and while I found a couple examples of people saying essentially the same thing I am I cannot find any official documentation stating this. Here are the responses I found though:
«The compiler is perfectly entitled to not know your logic.»
«. when there’s a control flow structure, it can’t evaluate the situation, because it’s not executing code, so it doesn’t know if the values are getting assigned.»
dteDest will not have a value set if currentDataObj == null
It will work if you change your line to:
compiler logic seems to be fooled by the use of a common TryParse function
This isn’t really your problem though. The problem comes in that the following line:
So in this case dteDest is never being set and the compiler feels this is a problem, even if you look at the logic and say that the code will never run if it is not set.
The simple fact is that people can often spot optimisation and special cases that are beyond the compiler. You sound like you are already aware that you can solve this simply just by checking the parameter at the beginning and then returning if its null.
How to fix ‘error CS0165: Use of unassigned local variable’ in XmlReader Switch Case
I try to read data from a Xml file. My plan is to save all students as an object of Student with the name and the semester.
I found a guide with XmlReader and switch case so i tried it.
My problem now is that Visual Studio Code gives me an error: error CS0165: Use of unassigned local variable ‘student’ (student.name in case «name»). I guess it is because there wouldn’t be a student.name if the code does not go into case «student». I tried with try catch but that didn’t helped me.
How can I achieve that every student gets his name and semester correct?
1 Answer 1
You only assign student in the «student» case; from the compiler’s point of view, student is unassigned at the start of the «name» and «semester» cases, so you can’t set properties on them. You might have knowledge that always comes first, but the compiler doesn’t know that. Also, from it’s view, the scope is separate for each element. But if you’re 100% sure that there’s always a between each then you could probably move the assignment around a little:
However, in reality, in most scenarios, I would strongly recommend using XmlSerializer or similar to parse the input into objects, and then just deal with them as objects.
Based on the xml layout in the question, this should work:
Not the answer you’re looking for? Browse other questions tagged c# xml xmlreader or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.11.12.40742
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Why did I get the compile error «Use of unassigned local variable»?
My code is the following
Why is there an error «Use of unassigned local variable tmpCnt»?
I know I didn’t explicitly initialize it, but due to Default Value Table a value type is initialized with 0 anyway. The reference also reminds me:
Remember that using uninitialized variables in C# is not allowed.
But why do I have to do it explicitly if it’s already done by default? Wouldn’t it gain performance if I wouldn’t have to do it?
10 Answers 10
Local variables aren’t initialized. You have to manually initialize them.
Members are initialized, for example:
But local variables are not:
So your code must be:
So the long and the short of it is, members are initialized, locals are not. That is why you get the compiler error.
Default assignments apply to class members, but not to local variables. As Eric Lippert explained it in this answer, Microsoft could have initialized locals by default, but they choose not to do it because using an unassigned local is almost certainly a bug.
The following categories of variables are classified as initially unassigned:
The following categories of variables are classified as initially assigned:
Use of unassigned local variable
I’ve got problem with writing a converter from hex to bin, dec to bin etc. Here’s my code, when I debug it I’ve got an error «Use of unassigned local variable Dec_Int10», could you help me? How can I fix this error?
7 Answers 7
You get that error because there is no default value assigned to the variable and since the only assignments to it are inside if blocks, the compiler thinks there is a chance the variable will never be assigned.
If you just initialize it to 0 you’ll no longer have the error.
This is one of the checks provided by the compiler to keep you from making easy-to-make mistakes.
You want to initialize your variables:
Otherwise the compiler doesn’t know if it has ever been assigned a value.
Either add an else statement or try initializing it to:
Declare Dec_Int10 to be equal to zero (or whatever default value you want it to have) when you declare it.
You simply have to change
since the compiler can’t verify that Dec_Int10 will be set before it’s used in another way.
adding an else would be the best thing to do. If you initialize it to begin with, you most likely will just reset the value. using the else will be more efficient.
Take a look at your code.
What happens if txtBox1,2,3 & 4 are ALL empty/null at the same time?
Nothing ever gets assigned to Dec_Int10. Thus later in the code you are attempt to convert an uninitialized variable. The compiler looks at the execution path and has determine that a scenario exists (such as all 4 if fail) that the variable isn’t initialized.
As others have indicated you can resolve it by using: int Dec_Int10 = 0;
The larger learning point is WHY it is happening?
This code for example won’t generate an error because no matter what the status of textbox 1,2,3,4 Dec_Int10 will be initilialized before conversion.