Ошибка компилятора cs0103

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0103

Compiler Error CS0103

07/20/2015

CS0103

CS0103

fd1f2104-a945-4dba-8137-8ef869826062

Compiler Error CS0103

The name ‘identifier’ does not exist in the current context

An attempt was made to use a name that does not exist in the class, namespace, or scope. Check the spelling of the name and check your using directives and assembly references to make sure that the name that you are trying to use is available.

This error frequently occurs if you declare a variable in a loop or a try or if block and then attempt to access it from an enclosing code block or a separate code block, as shown in the following example:

[!NOTE]
This error may also be presented when missing the greater than symbol in the operator => in an expression lambda. For more information, see expression lambdas.

using System;

class MyClass1
{
    public static void Main()
    {
        try
        {
            // The following declaration is only available inside the try block.
            var conn = new MyClass1();
        }
        catch (Exception e)
        {  
            // The following expression causes error CS0103, because variable
            // conn only exists in the try block.
            if (conn != null)
                Console.WriteLine("{0}", e);
        }
    }
}

The following example resolves the error:

using System;

class MyClass2
{
    public static void Main()
    {
        // To resolve the error in the example, the first step is to
        // move the declaration of conn out of the try block. The following
        // declaration is available throughout the Main method.
        MyClass2 conn = null;
        try
        {
            // Inside the try block, use the conn variable that you declared
            // previously.
            conn = new MyClass2();
        }
        catch (Exception e)
        {
            // The following expression no longer causes an error, because
            // the declaration of conn is in scope.
            if (conn != null)
                Console.WriteLine("{0}", e);
        }
    }
}

Только сегодня начал изучать C#, и вот столкнулся с ошибкой CS0103, Имя «а» не существует в текущем контексте. Гугл решение не рассказал, на удивление.

using System;

namespace C_Sharp

{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hi! Type your name here: ");
            try
            {
                int a = int.Parse(Console.ReadLine());
            }
            catch (Exception) {
                Console.WriteLine("Can't convert");
            }
            Console.WriteLine($"Thanks, {a}!");
            Console.ReadKey();
        }
    }
}

задан 5 мая 2020 в 19:56

Werflame Xij's user avatar

Переменная a у вас определена внутри блока try. Вне его она не видна.

Можно весь код поместить внутри блока:

public static void Main(string[] args)
{
    Console.WriteLine("Hi! Type your name here: ");
    try
    {
        int a = int.Parse(Console.ReadLine());
        Console.WriteLine($"Thanks, {a}!");
        Console.ReadKey();
    }
    catch (Exception) {
        Console.WriteLine("Can't convert");
    }
}

Или определить a до блока try-catch

public static void Main(string[] args)
{
    Console.WriteLine("Hi! Type your name here: ");
    int a;
    try
    {
        a = int.Parse(Console.ReadLine());
    }
    catch (Exception) {
        Console.WriteLine("Can't convert");
        return;
    }
    Console.WriteLine($"Thanks, {a}!");
    Console.ReadKey();
}

ответ дан 5 мая 2020 в 20:05

Кирилл Малышев's user avatar

Кирилл МалышевКирилл Малышев

10.8k1 золотой знак18 серебряных знаков34 бронзовых знака

  • Remove From My Forums
  • Вопрос

  • Hi,

    I’m hoping this is going to be an easy one for someone. I’m getting the following error when compiling a simple program in Visual Studio 2015 (Community Edition)

    Error CS0103 The name ‘File’ does not exist in the current context.

    Now, I can get this same code to compile successfully in Visual Studio 2013 (Express) Desktop

    The line I suspect the compiler is choking on is this one:

    StreamReader reader = new StreamReader(File.OpenRead(@»C:UsersxxxxxxxDesktoptest.csv»));

    So the question being; why do I get this error in Visual Studio 2015 (Community Edition) and not in Visual Studio 2013 (Express) Desktop. The code is exactly the same and has the following at the top:

    using System.IO;

    Is there a setting in Visual Studio 2015 (Community Edition) that would need changing ?

    Any help with this would be greatly appreciated.

    Thanks in adv.

Ответы

  • Thanks for your reply. I tried doing that before I posted to this forum, but the error remains in Visual Studio 2015 (Community Edition).

    I’ve managed to work this out.

    I edited the project.json file and removed the following from the frameworks:

    «dnxcore50»: {
                «dependencies»: {
                    «System.Collections»: «4.0.10-beta-23019»,
                    «System.Console»: «4.0.0-beta-23019»,
                    «System.Linq»: «4.0.0-beta-23019»,
                    «System.Threading»: «4.0.10-beta-23019»,
                    «Microsoft.CSharp»: «4.0.0-beta-23019»
                }
            }

    and just left the following:

    «dnx451»: { }

    Now the project compiles with no errors.

    Thanks for you time.

    • Изменено

      22 августа 2015 г. 10:55

    • Помечено в качестве ответа
      levens2m
      22 августа 2015 г. 10:56

Студворк — интернет-сервис помощи студентам

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

Код

CS0103: The name 'VehicleF' does not exist in the current context -> Class1.cs:16

Файл запуска сервера

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using GTANetworkAPI;
 
namespace NewProject
{
    public class Main : Script
    {
        [ServerEvent(Event.ResourceStart)]
        public void OnResourceStart()
        {
            NAPI.Util.ConsoleOutput("Сервер успешно запущен");
            NAPI.Server.SetDefaultSpawnLocation(new Vector3(386.4574, -750.8737, 29.29371));
            VehicleF.LoadVehicle();
        }
    }
}

Файл с функциями транспорта

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
using GTANetworkAPI;
 
namespace NewProject
{
    public class VehicleF : Script
    {
        public static void LoadVehicle()
        {
            NAPI.Vehicle.CreateVehicle(NAPI.Util.VehicleNameToModel("CarbonRS"), new Vector3(380.8715, -739.8875, 28.88084), 179, new Color(0, 255, 100), new Color(0));
            NAPI.Util.ConsoleOutput("[LOAD] Транспорт успешно запущен");
        }
    }
}

А так же где у меня идет работа с базой данных выходит ошибка

Код

 CS0012: The type 'DbConnection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
       -> connect.cs:15

Добавлено через 1 час 24 минуты
Большое спасибо вам, но я перехожу по вашим ссылкам, там такие же ответы на другие ссылки, а затем опять ответы со ссылками, где-то на 5 переходе я бросил это занятие, так как видимо ответов здесь не бывает -_-

Добавлено через 9 минут
Тем более меня не интересуют темы где люди не обьявляют переменные, меня интересует почему у меня методы из одного класса не вызываются в другом, классы по разным файлам

Добавлено через 16 минут
Если я прописываю два класса в одном файле то все хорошо, а если по разным то вот такие ошибки, может кто сказать как линкануть файл? Указать его вначале? Подключить? Я думал что если все одним проектом то таких проблем быть не должно, но видимо ошибся

C# Compiler Error

CS0103 – The name ‘identifier’ does not exist in the current context

Reason for the Error

You will usually receive this error when you are trying to use a identifier name in C# that doesnot exist with-in the current scope. One of the simple example of this error is when you declare a variable with-in a try block and try to access it in the catch block.

In the below example, the variable i is declared inside the try block, so its scope is restricted to the try block. When you try accessing it in the catch block is when you will receive the error.

using System;

public class DeveloperPublish
{
    public static void Main()
    {       
        try
        {
            int i = 1;
            int j = 0;
            int result = i / j;
        }
        catch(DivideByZeroException)
        {
            string message = i + " is divivided by zero";
            Console.WriteLine(message);
        }

    }
}

Error CS0103 The name ‘i’ does not exist in the current context ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active

Solution

To fix the error move the declaration of the identifier that is causing the error to a higher scope so that it is available when it is accessed.

For example, to fix the error in the above code snippet, we just need to move the declaration of the identifier outside of the try block.

using System;

public class DeveloperPublish
{
    public static void Main()
    {
        int i = 1;
        try
        {          
            int j = 0;
            int result = i / j;
        }
        catch(DivideByZeroException)
        {
            string message = i + " is divivided by zero";
            Console.WriteLine(message);
        }

    }
}

Possible Duplicate:
Razor-based view doesn’t see referenced assemblies

I am a Newbie in ASP.net
I am trying to connect to a database and I keep getting this error

**Compilation Error

Description: An error occurred during the compilation of a resource
required to service this request. Please review the following specific
error details and modify your source code appropriately.

Compiler Error Message: CS0103: The name ‘Database’ does not exist in
the current context

Source Error:

Line 1: @{
Line 2: var db = Database.Open(«demo»); ‘
Line 3:
Line 4:

Source File: c:UsersAyoyaDocumentsMy Web SitesdemoPage.cshtml
Line: 2
**

Can anyone tell me whats wrong?
Thank you

Community's user avatar

asked Jun 22, 2012 at 5:54

Aya Abdelsalam's user avatar

Aya AbdelsalamAya Abdelsalam

5023 gold badges8 silver badges21 bronze badges

0

The compiler’s already telling you what’s wrong — it doesn’t know what you mean by Database. Is that mean to be a property of the page, or is it the name of a type with a static Open method? It’s not clear from the code itself, and obviously the compiler can’t find the name either.

Work out what name you mean, then work out why the compiler can’t see it, then fix that. If you need more help on any of these steps, you’ll need to provide more information.

(As an aside, I completely agree with dbaseman: putting database calls in your view is a bad idea.)

answered Jun 22, 2012 at 6:00

Jon Skeet's user avatar

Jon SkeetJon Skeet

1.4m861 gold badges9099 silver badges9172 bronze badges

4

If you’re opening a database in your Razor view, that is completely the wrong approach. Your logic should go in the Controller, not the View. Consider creating a «view model» class that contains all the data needed for your view, and populate that class from the Controller.

Probably the reason this piece of code isn’t working is that you will need to specify the full namespace of Database. I’m not sure what that class is, though; if it’s in a separate DLL, you’ll have more problems. Again, though, you should circumvent this problem by putting your database logic in the controller.

answered Jun 22, 2012 at 6:00

McGarnagle's user avatar

McGarnagleMcGarnagle

101k31 gold badges228 silver badges260 bronze badges

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора cs0030
  • Ошибка компиляции для платы generic esp8266 module
  • Ошибка компилятора cs0029
  • Ошибка компиляции для платы esp32 wrover module
  • Ошибка компилятора cs0021