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:
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.12.10.40971
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
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.
use of unassigned local variable c# [duplicate]
i have declared a variable in the beginning of program. i believe the variable is declared and used within the scope of the program.
i can check the value of u stored via debugging mode but could not use it elsewhere «use of unassigned local variable u» should i use decimal instead? i trued using decimal but since i also used
somewhere else in the program i dont think there is Convert.toDecimal() available in c#; what is the difference between double and decimal. PS: I have never used decimal before
5 Answers 5
In C#, the use of uninitialized variables is not allowed. If you do not assign a default value, or use a constructor, the compiler won’t know what your value is and therefore cannot use it.
As a side note, declaring variables on their own line is also a good practice in C#. So is declaring the loop variable directly in the for statement. I’d also recommend using meaningful variable names ( a and u are not obvious for everyone), readability is pretty important.
what is the difference between double and decimal.
decimal is usually used for currency or financial operations because of its greater precision (28-29 digits, compared to 15-16 for double). However, it have a much much smaller range than double. decimal range goes up to 7.9 x 10^28, while double goes up to 1.7 x 10^308.
On the other hand, if you don’t need great precision or great range, float would be the best type to use as it is 32-bit (compared to 64 for double).
Why compiler throw error CS0165: Use of unassigned local variable?
I put the code below, and also uploaded to a online c# compiler: jdoodle.com/a/1jww the code can compile and run online, however, it doesn’t compile in my local visual studio.
Language version c# 7.3
Microsoft (R) Visual C# Compiler version 2.10.0.0 (b9fb1610)
expecting to see Hello1 in Console.Output Because if the condition is true, the Null-Conditional check must have returned a non-null value, and the key is existing in the dictionary and the value must have been assigned when returning from the TryGetValue method.
the called method is required to assign a value before the method returns.
update: This is an open issue in https://github.com/dotnet/roslyn/issues/32572
I think it’s an true issue/bug if the requirement for compiler includes not to give false alarm. My arguments:
Whenever CPU executing to the point inside the if bracket code block, the value must have returned from TryGetValue call and is NOT «unassigned local variable». An easier solution is to give something like «unable to determine assignment status» as warning instead of error, if compiler can’t look forward for assignment status when interpreting null conditional operator.
4 Answers 4
It’s due to the compiler difference.
In this fiddle, https://dotnetfiddle.net/5GgGNS, you can see the error, which is omitted in the mono compiler.
I think the error is valid due to the fact that this line
If you would rewrite it to:
Now, the null value, or true in your case, could be a function’s return value, which would only be known at run time.
But, since all variables are basically always initialized, it’s just a compiler feature.
On the other hand, according to the C#5 specs:
A local variable introduced by a local-variable-declaration is not automatically initialized and thus has no default value. For the purpose of definite assignment checking, a local variable introduced by a local-variable-declaration is considered initially unassigned. A local-variable-declaration may include a local-variable-initializer, in which case the variable is considered definitely assigned only after the initializing expression (§5.3.3.4).
But your code is C# 6.
Argumentation
Fun fact, if you use this code:
The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn’t execute.
So, since value is initialized, on run-time, the question remains if it’s a valid compiler error at build time. Regarding to the run-time intend of the code it is (and that’s why the error was there in the first place), but I think it remains a grey area.
Do note that according to this default(T) is not override-able, which would actually lead to no condition where it fails.
By running this little test:
The output becomes: