description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Compiler Error CS0165 |
Compiler Error CS0165 |
07/20/2015 |
CS0165 |
CS0165 |
e7eb7c90-af16-4734-b747-214030696975 |
Compiler Error CS0165
Use of unassigned local variable ‘name’
The C# compiler doesn’t allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165. For more information, see Fields. This error is generated when the compiler encounters a construct that might result in the use of an unassigned variable, even if your particular code does not. This avoids the necessity of overly complex rules for definite assignment.
For more information, see Why does a recursive lambda cause a definite assignment error?.
Example 1
The following sample generates CS0165:
// CS0165.cs using System; class MyClass { public int i; } class MyClass2 { public static void Main(string[] args) { // i and j are not initialized. int i, j; // You can provide a value for args[0] in the 'Command line arguments' // text box on the Debug tab of the project Properties window. if (args[0] == "test") { i = 0; } // If the following else clause is absent, i might not be // initialized. //else //{ // i = 1; //} // Because i might not have been initialized, the following // line causes CS0165. j = i; // To resolve the error, uncomment the else clause of the previous // if statement, or initialize i when you declare it. // The following example causes CS0165 because myInstance is // declared but not instantiated. MyClass myInstance; // The following line causes the error. myInstance.i = 0; // To resolve the error, replace the previous declaration with // the following line. //MyClass myInstance = new MyClass(); } }
Example 2
Compiler error CS0165 can occur in recursive delegate definitions. You can avoid the error by defining the delegate in two statements so that the variable is not used before it is initialized. The following example demonstrates the error and the resolution.
class Program { delegate void Del(); static void Main(string[] args) { // The following line causes CS0165 because variable d is used // as an argument before it has been initialized. Del d = delegate() { System.Console.WriteLine(d); }; //// To resolve the error, initialize d in a separate statement. //Del d = null; //// After d is initialized, you can use it as an argument. //d = delegate() { System.Console.WriteLine(d); }; //d(); } }
xref:System.Reflection.Assembly.Load(System.String)
adessolv 2 / 1 / 1 Регистрация: 14.06.2020 Сообщений: 33 |
||||
1 |
||||
02.09.2020, 02:18. Показов 5513. Ответов 14 Метки нет (Все метки)
Добрый вечер! Есть метод, добавляющий пассажиров автобуса — ввод возраста и пола с клавиатуры, после чего из файла берется случайное имя и приписывается этому пассажиру. Работает, пока не проставлен if, который должен на основе newGender выбирать один из 3 файлов (мужские, женские и унисекс имена). Кликните здесь для просмотра всего текста
Что здесь не так? Вроде бы newName присваивается значение от random_item… Спасибо!
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
02.09.2020, 02:18 |
14 |
6318 / 3936 / 1578 Регистрация: 09.05.2015 Сообщений: 9,237 |
|
02.09.2020, 02:48 |
2 |
Что здесь не так? Вроде бы newName присваивается значение от random_item… Какое будет значение у
0 |
adessolv 2 / 1 / 1 Регистрация: 14.06.2020 Сообщений: 33 |
||||
02.09.2020, 12:04 [ТС] |
3 |
|||
Какое будет значение у newName если код внутри if не выполнится? Действительно… Но перед этим же newGender принимает значение. Тогда по идее вот так должно работать Кликните здесь для просмотра всего текста
Однако периодически для любого пола используются имена из списка Queer. То есть — newGender почему-то не срабатывает. Что надо править?
0 |
17225 / 12677 / 3323 Регистрация: 17.09.2011 Сообщений: 20,949 |
|
02.09.2020, 12:26 |
4 |
Но перед этим же newGender принимает значение. Там бесконечный цикл, выход из которого происходит только тогда, когда этой переменной присвоено значение.
Тогда по идее вот так должно работать А зачем присваивать переменной одно и то же значение в каждой ветке?
используются имена из списка Queer. То есть — newGender Как прогрессивно, толерантно и рукопожатно!!!1
0 |
adessolv 2 / 1 / 1 Регистрация: 14.06.2020 Сообщений: 33 |
||||
02.09.2020, 13:06 [ТС] |
5 |
|||
Там бесконечный цикл Я не понимаю
А зачем присваивать переменной одно и то же значение в каждой ветке? переменной newGender или newName?
Как прогрессивно, толерантно и рукопожатно
А вот сейчас ругается на newName в цикле for: Кликните здесь для просмотра всего текста
И я теперь вообще не понимаю, почему так
0 |
kolorotur 17225 / 12677 / 3323 Регистрация: 17.09.2011 Сообщений: 20,949 |
||||||||||||
02.09.2020, 13:30 |
6 |
|||||||||||
Где именно он бесконечный? Вот тут:
переменной newGender или newName? Вот здесь у вас во всех ветках происходит одно и то же за исключением файла, из которого считываются имена.
Зачем столько дублирования?
А вот сейчас ругается на newName в цикле for Все по той же причине: компилятор не может гарантировать, что до выполнения этой строчки переменной будет присвоено значение.
1 |
2 / 1 / 1 Регистрация: 14.06.2020 Сообщений: 33 |
|
02.09.2020, 13:42 [ТС] |
7 |
Вот тут: лучше сделать switch от userInput, где в зависимости от нажатой буквы будет выбирать правильный пол?
// Кстати, почему первая строчка файла всегда пропускается? надо 0 вместо 1? При тестировании он один раз выбрал какую-то пустую строку и не определил имя
0 |
17225 / 12677 / 3323 Регистрация: 17.09.2011 Сообщений: 20,949 |
|
02.09.2020, 14:34 |
8 |
лучше сделать switch от userInput, где в зависимости от нажатой буквы будет выбирать правильный пол? Как вариант, но что-то мне кажется, что с современными трендами вам клавиатуры не хватит для букв…
надо 0 вместо 1? Ну 0 — это первая строчка, да.
При тестировании он один раз выбрал какую-то пустую строку и не определил имя Это уже после выбора надо проверять.
0 |
2 / 1 / 1 Регистрация: 14.06.2020 Сообщений: 33 |
|
02.09.2020, 14:37 [ТС] |
9 |
с современными трендами вам клавиатуры не хватит для букв… хаха
0 — это первая строчка Понятно, либо в каждом файле делать 1 строку пустой Ближе к вечеру все проверю, но идея мне ясна. Спасибо!
0 |
adessolv 2 / 1 / 1 Регистрация: 14.06.2020 Сообщений: 33 |
||||||||
02.09.2020, 21:56 [ТС] |
10 |
|||||||
Все-таки ничего хорошего не получилось… Кликните здесь для просмотра всего текста
Попытки сделать вот так
не удались из-за switch. Но хотя бы теперь чуть короче код. Теперь у меня полный ступор, и не понимаю, зачем все это. Помогите, пожалуйста!?
0 |
kotelok 1008 / 626 / 213 Регистрация: 08.08.2014 Сообщений: 1,947 |
||||
03.09.2020, 08:28 |
11 |
|||
Решениеadessolv Кликните здесь для просмотра всего текста
Добавлено через 23 минуты For the purpose of definite assignment checking, a local variable introduced by a local_variable_declaration is considered initially unassigned. (c) https://docs.microsoft.com/en-… /variables (раздел Local Variables).
1 |
2 / 1 / 1 Регистрация: 14.06.2020 Сообщений: 33 |
|
03.09.2020, 13:00 [ТС] |
12 |
kotelok, спасибо! А не могли бы вы сказать, что именно означает Код while (string.IsNullOrEmpty(newGender)) и Код switch (Console.ReadKey(false).Key) ? Точнее, что здесь проверяется?
0 |
1008 / 626 / 213 Регистрация: 08.08.2014 Сообщений: 1,947 |
|
03.09.2020, 13:09 |
13 |
1. Цикл будет выполняться до тех пор, пока в теле цикла переменной ‘newGender’ не будет присвоено какой-нибудь значение, кроме null или пустой строки.
0 |
2 / 1 / 1 Регистрация: 14.06.2020 Сообщений: 33 |
|
03.09.2020, 13:25 [ТС] |
14 |
2. Производится считывание одного нажатия клавиши, берётся её строковое представление. Если строковое представление одно из [X,Y,Q], то переменной ‘newGender’ присваивается одно из значений и на следующей проверке условия цикла цикл завершается. Спасибо! То есть, если нажата какая-то другая клавиша — цикл начинается заново и длится до тех пор, пока newGender не будет присвоено значение Female, Male или Queer?
0 |
1008 / 626 / 213 Регистрация: 08.08.2014 Сообщений: 1,947 |
|
03.09.2020, 13:28 |
15 |
adessolv Попробуйте запустить код в отладке, пройтись по шагам и посмотреть значения переменных на каждом этапе. Станет намного понятнее, да и опыт работы с отладчиком будет весьма полезен в любых задачах.
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
03.09.2020, 13:28 |
Помогаю со студенческими работами здесь Использование локальной переменной «b1», которой не присвоено значение Использование локальной переменной «*», которой не присвоено значение Ошибка 1 Использование локальной переменной «stat», которой не присвоено значение
Не могу исправить ошибку «использование локальной переменной которой не присвоено значение» при создании Word using… Не понятная ошибка «Использование локальное переменной, которой не присвоено значение» Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 15 |
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 (myDict?.TryGetValue("hello", out var value) == true)
is not guaranteed to initialize the local variable value
.
If you would rewrite it to:
if (myDict?.TryGetValue("hello", out var value) == null)
it would try to access value
.
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.
So my conclusion is that the compilers interpret it differently. The Microsoft compiler takes the ?.
operator into account. You should file it as a bug, or finding at least, maybe even at both parties.
Argumentation
Fun fact, if you use this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
//Your code goes here
Dictionary<string,int> myDict = null;
if (myDict?.TryGetValue("hello", out var value) == null)
{
Console.WriteLine("Hello" + value.ToString());
}
}
}
[using https://www.jdoodle.com/compile-c-sharp-online , mono 5.10.1]
You’ll see the actual initialization to default(T)
at work. The output is Hello0
. Nevertheless, it’s remarkable because due to the ?
, and the fact that myDict
is null
, TryGetValue
shouldn’t be called and leaving value
«uninitialized».
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.
source
But…, since there are no uninitialized variables; if it compiles, the compiler will make sure it’s behavior is not undefined.
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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
//Your code goes here
Dictionary<string,int> myDict = null;
if (myDict?.Bar(out var test) == null)
{
Console.WriteLine("does hit");
}
}
}
static class Foo
{
public static object Bar(this Dictionary<string,int> input, out int test)
{
test = 3;
Console.WriteLine("does not hit");
return 1;
}
}
[using https://www.jdoodle.com/compile-c-sharp-online , mono 5.10.1]
The output becomes:
does hit
And you can verify the correct run-time behavior of the ?.
operator.
В первом варианте
int a=1;
int b; //не инициализировано
switch(a){
case 1:
b=100;
Console.WriteLine ("изнутри "+b);
break;
}//если a != 1, то b всё ещё не инициализировано
Console.WriteLine ("снаружи "+b); //<-тут ошибка
Как вариант, если не хочется инициализировать b сразу, то можно добавить ветку default в switch:
int a=1;
int b;
switch(a){
case 1:
b=100;
Console.WriteLine ("изнутри "+b);
break;
default:
b = -1;
break;
}
Console.WriteLine ("снаружи "+b);
Ещё я бы посоветовал использовать switch-expression из C# 8 — он сразу исключает такой класс ошибок
var a = 1;
var b = a switch {
1 => 100,
_ => -1 // Если не добавить эту ветку, то будет ошибка, что switch-expression покрывает не все возможные варианты
};
//b гарантированно инициализировано
C# Compiler Error
CS0165 – Use of unassigned local variable ‘name’
Reason for the Error
You will receive this error when the C# compiler detects that you have used an uninitialized variables with-in your program.
For example, the below code snippet results in the error code CS0165 because the variable val is not initialized.
using System; namespace ConsoleApp2 { class Program { public static void Main() { int val; Console.WriteLine(val); } } }
Error CS0165 Use of unassigned local variable ‘val’ ConsoleApp2 C:UsersSenthilsourcereposConsoleApp1ConsoleApp2Program.cs 10 Active
Solution
C# doesnot allow you to use uninitialized variables. You will need to initialize the variable to a default value before you want to use them in your C# code.