Ошибка cs0165 использование локальной переменной которой не присвоено значение

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 файлов (мужские, женские и унисекс имена).
Если раскомментировать if, появляется ошибка в
pass[i] = new Passenger(newName, newAge, newGender); — Использование локальной переменной «newName», которой не присвоено значение (CS0165)

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
        public void add_passenger()
        {
            string newName;
            int newAge;
            string newGender;
            
            Console.WriteLine("-------------------------------------");
            Console.WriteLine("Add a new passenger");
                    
            while (true) {
                Console.WriteLine("Enter age:");
                try {
                    newAge = int.Parse(Console.ReadLine());
                    if (newAge < 0) {
                        Console.WriteLine("Please enter the positive age!");
                    } else {
                        break;
                    }
                    
                } catch (FormatException) {
                    Console.WriteLine("Please write an number.");
                }
            }
            
            while (true) {
                Console.WriteLine("Enter gender (Female, Male or Queer):");
                try {
                    newGender = Console.ReadLine();
                    break;
                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                }
            }
            
            if (newGender == "X" || newGender == "x") {
                newGender = "Female";
            }
            
            if (newGender == "Y" || newGender == "y") {
                newGender = "Male";
            }
            
            if (newGender == "Q" || newGender == "q") {
                newGender = "Queer";
            }
            
 
                Console.WriteLine("Assigning a random name:");
 
//              if (newGender == "Female")
//              {
                string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenFemale_names.txt");
                Random rand = new Random();
                string random_item = lines[rand.Next(lines.Length)];
                Console.WriteLine(random_item);
                newName = random_item;
                
//          }
            
            
            for (int i = 0; i < pass.Length - 1; i++) {
                if (pass[i] == null) {
                    pass[i] = new Passenger(newName, newAge, newGender);
                    break;
                } else {
                    continue;
                }
            }
            
            boarding_fee = boarding_fee + 20;
            pass_boarded = pass_boarded + 1;
            Console.WriteLine();
        }

Что здесь не так? Вроде бы newName присваивается значение от random_item…

Спасибо!



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

02.09.2020, 02:18

14

Эксперт .NET

6318 / 3936 / 1578

Регистрация: 09.05.2015

Сообщений: 9,237

02.09.2020, 02:48

2

Цитата
Сообщение от adessolv
Посмотреть сообщение

Что здесь не так? Вроде бы newName присваивается значение от random_item…

Какое будет значение у newName если код внутри if не выполнится?



0



adessolv

2 / 1 / 1

Регистрация: 14.06.2020

Сообщений: 33

02.09.2020, 12:04

 [ТС]

3

Какое будет значение у newName если код внутри if не выполнится?

Действительно… Но перед этим же newGender принимает значение. Тогда по идее вот так должно работать

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
if (newGender == "Female")
                {
                string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenFemale_names.txt");
                Random rand = new Random();
                string random_item = lines[rand.Next(1, lines.Length)];
                newName = random_item;
                }
                if (newGender == "Male")
                {
                    string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenMale_names.txt");
                    Random rand = new Random();
                    string random_item = lines[rand.Next(1, lines.Length)];
                    newName = random_item;
                }
                if (newGender == "Queer")
                {
                    string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt");
                    Random rand = new Random();
                    string random_item = lines[rand.Next(1, lines.Length)];
                    newName = random_item;
                }
                else {
                    string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt");
                    Random rand = new Random();
                    string random_item = lines[rand.Next(1, lines.Length)];
                    newName = random_item;
                }

Однако периодически для любого пола используются имена из списка Queer. То есть — newGender почему-то не срабатывает. Что надо править?



0



Эксперт .NET

17225 / 12677 / 3323

Регистрация: 17.09.2011

Сообщений: 20,949

02.09.2020, 12:26

4

Цитата
Сообщение от adessolv
Посмотреть сообщение

Но перед этим же newGender принимает значение.

Там бесконечный цикл, выход из которого происходит только тогда, когда этой переменной присвоено значение.
Из этого компилятор делает вполне корректный вывод, что далее по коду невозможно использовать переменную newGender с неприсвоенным значением.

Цитата
Сообщение от adessolv
Посмотреть сообщение

Тогда по идее вот так должно работать

А зачем присваивать переменной одно и то же значение в каждой ветке?
Если одно и то же значение присваивается вне зависимости от условия, то почему бы его не присвоить один раз перед условием или после него?

Цитата
Сообщение от adessolv
Посмотреть сообщение

используются имена из списка Queer. То есть — newGender

Как прогрессивно, толерантно и рукопожатно!!!1



0



adessolv

2 / 1 / 1

Регистрация: 14.06.2020

Сообщений: 33

02.09.2020, 13:06

 [ТС]

5

Цитата
Сообщение от kolorotur
Посмотреть сообщение

Там бесконечный цикл

Я не понимаю . Где именно он бесконечный?

Цитата
Сообщение от kolorotur
Посмотреть сообщение

А зачем присваивать переменной одно и то же значение в каждой ветке?

переменной newGender или newName?

Цитата
Сообщение от kolorotur
Посмотреть сообщение

Как прогрессивно, толерантно и рукопожатно

у меня шведский учебный курс — иначе здесь никак

А вот сейчас ругается на newName в цикле for:

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
            switch (newGender)
            {
                case "X":
                case "x":
                    newGender = "Female";
                    break;
                    
                case "Y":
                case "y":
                    newGender = "Male";
                    break;
                    
                case "Q":
                case "q":
                    newGender = "Queer";
                    break;
            }
            
            Console.WriteLine(newGender);
 
            Console.WriteLine("Assigning a random name:");
 
            switch (newGender)
            {
                case "Female":
                string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenFemale_names.txt");
                Random rand = new Random();
                string random_item = lines[rand.Next(1, lines.Length)];
                newName = random_item;
                Console.WriteLine(newName);
                break;
                
            case "Male":
                string[] lines2 = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenMale_names.txt");
                Random rand2 = new Random();
                string random_item2 = lines2[rand2.Next(1, lines2.Length)];
                newName = random_item2;
                Console.WriteLine(newName);
                break;
                
            case "Queer":
                string[] lines3 = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt");
                Random rand3 = new Random();
                string random_item3 = lines3[rand3.Next(1, lines3.Length)];
                newName = random_item3;
                Console.WriteLine(newName);
                break;
            }
            
            for (int i = 0; i < pass.Length - 1; i++) {
                if (pass[i] == null) {
                    pass[i] = new Passenger(newName, newAge, newGender);
                    break;
                } else {
                    continue;
                }
            }

И я теперь вообще не понимаю, почему так



0



kolorotur

Эксперт .NET

17225 / 12677 / 3323

Регистрация: 17.09.2011

Сообщений: 20,949

02.09.2020, 13:30

6

Цитата
Сообщение от adessolv
Посмотреть сообщение

Где именно он бесконечный?

Вот тут:

Цитата
Сообщение от adessolv
Посмотреть сообщение

C#
1
while (true) {

Цитата
Сообщение от adessolv
Посмотреть сообщение

переменной newGender или newName?

Вот здесь у вас во всех ветках происходит одно и то же за исключением файла, из которого считываются имена.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
                newName = random_item;
                }
                if (newGender == "Male")
                {
                    string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenMale_names.txt");
                    Random rand = new Random();
                    string random_item = lines[rand.Next(1, lines.Length)];
                    newName = random_item;
                }
                if (newGender == "Queer")
                {
                    string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt");
                    Random rand = new Random();
                    string random_item = lines[rand.Next(1, lines.Length)];
                    newName = random_item;
                }
                else {
                    string[] lines = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt");
                    Random rand = new Random();
                    string random_item = lines[rand.Next(1, lines.Length)];
                    newName = random_item;
                }

Зачем столько дублирования?

C#
1
2
3
4
5
6
7
8
9
10
11
string namesFile = newGender switch
{
   // А чего в Швеции так женщин обижают?
   "Male" => @"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenMale_names.txt".
   "Queer" => @"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt",
   _ => @"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt"
};
 
var rand = new Random();
var lines = File.ReadAllLnes(namesFile);
var newName = lines[rand.Next(1, lines.Length)]; // Кстати, почему первая строчка файла всегда пропускается?

Цитата
Сообщение от adessolv
Посмотреть сообщение

А вот сейчас ругается на newName в цикле for

Все по той же причине: компилятор не может гарантировать, что до выполнения этой строчки переменной будет присвоено значение.



1



2 / 1 / 1

Регистрация: 14.06.2020

Сообщений: 33

02.09.2020, 13:42

 [ТС]

7

Цитата
Сообщение от kolorotur
Посмотреть сообщение

Вот тут:

лучше сделать switch от userInput, где в зависимости от нажатой буквы будет выбирать правильный пол?

Цитата
Сообщение от kolorotur
Посмотреть сообщение

// Кстати, почему первая строчка файла всегда пропускается?

надо 0 вместо 1? При тестировании он один раз выбрал какую-то пустую строку и не определил имя



0



Эксперт .NET

17225 / 12677 / 3323

Регистрация: 17.09.2011

Сообщений: 20,949

02.09.2020, 14:34

8

Цитата
Сообщение от adessolv
Посмотреть сообщение

лучше сделать switch от userInput, где в зависимости от нажатой буквы будет выбирать правильный пол?

Как вариант, но что-то мне кажется, что с современными трендами вам клавиатуры не хватит для букв…

Цитата
Сообщение от adessolv
Посмотреть сообщение

надо 0 вместо 1?

Ну 0 — это первая строчка, да.
Если ее всегда надо пропускать, то 1 пойдет.

Цитата
Сообщение от adessolv
Посмотреть сообщение

При тестировании он один раз выбрал какую-то пустую строку и не определил имя

Это уже после выбора надо проверять.



0



2 / 1 / 1

Регистрация: 14.06.2020

Сообщений: 33

02.09.2020, 14:37

 [ТС]

9

Цитата
Сообщение от kolorotur
Посмотреть сообщение

с современными трендами вам клавиатуры не хватит для букв…

хаха мне всего лишь 3 надо, так что, думаю, тут хватит.

Цитата
Сообщение от kolorotur
Посмотреть сообщение

0 — это первая строчка

Понятно, либо в каждом файле делать 1 строку пустой

Ближе к вечеру все проверю, но идея мне ясна. Спасибо!



0



adessolv

2 / 1 / 1

Регистрация: 14.06.2020

Сообщений: 33

02.09.2020, 21:56

 [ТС]

10

Все-таки ничего хорошего не получилось…
Теперь ругается на неприсвоенное значение newName, newGender и userInput. Думаю про убрать while, но тогда, боюсь, что программа не разрешит ввести значение второй раз… или все же разрешит?

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
        string newName;
            int newAge;
            string newGender;
            ConsoleKeyInfo userInput;
            
            Console.WriteLine("-------------------------------------");
            Console.WriteLine("Add a new passenger");
                    
            do {
                Console.WriteLine("Enter age:");
                try {
                    newAge = int.Parse(Console.ReadLine());
                    if (newAge < 0) {
                        Console.WriteLine("Please enter the positive age!");
                    } else {
                        break;
                    }
                    
                } catch (FormatException) {
                    Console.WriteLine("Please write an number.");
                }
            } while (true);
            
            while (true) {
                Console.WriteLine("Enter gender (Female, Male or Queer):");
                try {
                    userInput = Console.ReadKey(true);
                    
                    break;
                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                    break;
                }
            
            }
            
            switch (userInput.Key)
            {
                case ConsoleKey.X:
                
                    newGender = "Female";
                    break;
                    
                case ConsoleKey.Y:
                
                    newGender = "Male";
                    break;
                    
                case ConsoleKey.Q:
                
                    newGender = "Queer";
                    break;
            }
            
            Console.WriteLine(newGender);
 
            Console.WriteLine("Assigning a random name:");
            
            string[] female_names = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenFemale_names.txt");
            string[] male_names = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenMale_names.txt");
            string[] queer_names = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt");
            Random rand = new Random();
            
            switch (newGender)
            {
                case "Female":
                    
                    string female_name = female_names[rand.Next(0, female_names.Length)];
                    Console.WriteLine(female_name);
                    newName = female_name;
                    break;
                    
                case "Male":
                    string male_name = male_names[rand.Next(0, male_names.Length)];
                    Console.WriteLine(male_name);
                    newName = male_name;
                    break;
                    
                case "Queer":
                    string queer_name = queer_names[rand.Next(0, queer_names.Length)];
                    Console.WriteLine(queer_name);
                    newName = queer_name;
                    break;
                    
            }
            
            Console.WriteLine(newName);
 
            
            for (int i = 0; i < pass.Length - 1; i++) {
                if (pass[i] == null) {
                    pass[i] = new Passenger(newName, newAge, newGender);
                    break;
                } else {
                    continue;
                }
            }

Попытки сделать вот так

C#
1
2
3
4
5
6
7
8
string namesFile = newGender switch
{
 ....
};
 
var rand = new Random();
var lines = File.ReadAllLnes(namesFile);
var newName = lines[rand.Next(1, lines.Length)];

не удались из-за switch. Но хотя бы теперь чуть короче код.

Теперь у меня полный ступор, и не понимаю, зачем все это.

Помогите, пожалуйста!?



0



kotelok

1008 / 626 / 213

Регистрация: 08.08.2014

Сообщений: 1,947

03.09.2020, 08:28

11

Лучший ответ Сообщение было отмечено adessolv как решение

Решение

adessolv

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    public static void AddPassenger()
    {
        string newName;
        int newAge;
        string newGender = string.Empty;
 
        Console.WriteLine("-------------------------------------");
        Console.WriteLine("Add a new passenger");
 
        do
        {
            Console.WriteLine();
            Console.Write("Enter age: ");
            try
            {
                newAge = int.Parse(Console.ReadLine());
                if (newAge < 0)
                {
                    Console.WriteLine("Please enter the positive age!");
                }
                else
                {
                    break;
                }
 
            }
            catch (FormatException)
            {
                Console.WriteLine("Please write an number.");
            }
        } while (true);
 
 
        while (string.IsNullOrEmpty(newGender))
        {
            Console.WriteLine();
            Console.Write("Enter gender (Female[X], Male[Y] or Queer[Q]): ");
            switch (Console.ReadKey(false).Key)
            {
                case ConsoleKey.X:
                    newGender = "Female";
                    break;
 
                case ConsoleKey.Y:
                    newGender = "Male";
                    break;
 
                case ConsoleKey.Q:
                    newGender = "Queer";
                    break;
            }
        }
 
        Console.WriteLine(newGender);
 
        Console.WriteLine("Assigning a random name:");
 
        string[] female_names = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenFemale_names.txt");
        string[] male_names = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenMale_names.txt");
        string[] queer_names = File.ReadAllLines(@"C:UsersadessDocumentsSharpDevelop ProjectsbussenBussenBussenQueer_names.txt");
        Random rand = new Random();
 
        switch (newGender)
        {
            case "Female":
 
                string female_name = female_names[rand.Next(0, female_names.Length)];
                Console.WriteLine(female_name);
                newName = female_name;
                break;
            case "Male":
                string male_name = male_names[rand.Next(0, male_names.Length)];
                Console.WriteLine(male_name);
                newName = male_name;
                break;
 
            case "Queer":
                string queer_name = queer_names[rand.Next(0, queer_names.Length)];
                Console.WriteLine(queer_name);
                newName = queer_name;
                break;
            default:
                throw new Exception("Unknown gender: " + newGender);
        }
 
        Console.WriteLine(newName);
 
 
        for (int i = 0; i < pass.Length - 1; i++)
        {
            if (pass[i] == null)
            {
                pass[i] = new Passenger(newName, newAge, newGender);
                break;
            }
            else
            {
                continue;
            }
        }
    }

Добавлено через 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 или пустой строки.
2. Производится считывание одного нажатия клавиши, берётся её строковое представление. Если строковое представление одно из [X,Y,Q], то переменной ‘newGender’ присваивается одно из значений и на следующей проверке условия цикла цикл завершается.



0



2 / 1 / 1

Регистрация: 14.06.2020

Сообщений: 33

03.09.2020, 13:25

 [ТС]

14

Цитата
Сообщение от kotelok
Посмотреть сообщение

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
Да, если нажата любая другая клавиша, то ни одна из case-веток не выполнится и значение ‘newGender’ останется без изменений.

Попробуйте запустить код в отладке, пройтись по шагам и посмотреть значения переменных на каждом этапе. Станет намного понятнее, да и опыт работы с отладчиком будет весьма полезен в любых задачах.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

03.09.2020, 13:28

Помогаю со студенческими работами здесь

Использование локальной переменной «b1», которой не присвоено значение
Всем привет!
Изучаю книгу Шилд Г. &quot;полное руководство C# 4.0&quot;
Не получается скомпилировать код…

Использование локальной переменной «*», которой не присвоено значение
Создал чистую форму на С#, и добавил туда класс.
А когда пытаюсь объявить экземпляр класса, пишет…

Ошибка 1 Использование локальной переменной «stat», которой не присвоено значение
Объявляю массив string stat;
Потом требуется проверка. Пишу if (stat==null)
и он мне жалуется на…

Не работает метод класса: Использование локальной переменной «cir», которой не присвоено значение
Всем привет,
Простая программа, но не работает метод set, пишет :
Ошибка CS0165 Использование…

Не могу исправить ошибку «использование локальной переменной которой не присвоено значение» при создании Word
Помогите найти ошибку пытаюсь повторить со статьи. Должно работать а выдает ошибку

using…

Не понятная ошибка «Использование локальное переменной, которой не присвоено значение»
private static double nCalc(double vgvsvalue, double widthvalue, double heightvalue, double…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

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);
                 
        }

    }
    
}

C# Error CS0165 – Use of unassigned local variable 'name'

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.

Понравилась статья? Поделить с друзьями:
  • Ошибка cs0106 модификатор public недопустим для этого элемента
  • Ошибка cs0106 модификатор private недопустим для этого элемента
  • Ошибка cs0103 имя initializecomponent не существует в текущем контексте
  • Ошибка cs0101 пространство имен уже содержит определение для
  • Ошибка cs0004 pubg на ps4