Error cs0103 the name console does not exist in the current context

This repository contains .NET Documentation. Contribute to dotnet/docs development by creating an account on GitHub.

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

So i’m having this problem.

I’m trying to compile code in memory and adding namespace references by searching the syntax tree so i do not add them manually. Trying to simulate how Visual Studio maybe does it.

I’m a bit over my head in the compilation department. Even if i add a metadata reference to System while reading the syntax tree it does not find System.Console.

The key is that i want it to include the assemblies by itself, i do not want to add a «MetadataReference.CreateFromFile(….,»System.Console»).

I explained the code below so that is clear what is happening.

class App
{
    static void Main(string[] args)
    {
        //creating the syntax tree for the program
        SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
            namespace ns{
                using System;
                public class App{
                    public static void Main(string[] args){
                        Console.Write(""dada"");
                    }
                }


            }");
        //creating options that tell the compiler to output a console application
        var options = new CSharpCompilationOptions(
           OutputKind.ConsoleApplication,
           optimizationLevel: OptimizationLevel.Debug,
           allowUnsafe: true);

        //creating the compilation
        var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), options: options);

        //adding the syntax tree
        compilation = compilation.AddSyntaxTrees(syntaxTree);

        //getting the local path of the assemblies
        var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
        List<MetadataReference> references = new List<MetadataReference>();
        //adding the core dll containing object and other classes
        references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Private.CoreLib.dll")));
        references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")));
        //gathering all using directives in the compilation
        var usings = compilation.SyntaxTrees.Select(tree => tree.GetRoot().ChildNodes().OfType<UsingDirectiveSyntax>()).SelectMany(s => s).ToArray();

        //for each using directive add a metadatareference to it
        foreach (var u in usings)
        {
            references.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, u.Name.ToString() + ".dll")));
        }

        //add the reference list to the compilation
        compilation=compilation.AddReferences(references);

        //compile
        using (var ms = new MemoryStream())
        {
            EmitResult result = compilation.Emit(ms);

            if (!result.Success)
            {
                IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                    diagnostic.IsWarningAsError ||
                    diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    Console.Error.WriteLine("{0}: {1}, {2}", diagnostic.Id, diagnostic.GetMessage(), diagnostic.Location);
                }
            }
            else
            {
                ms.Seek(0, SeekOrigin.Begin);
                AssemblyLoadContext context = AssemblyLoadContext.Default;
                Assembly assembly = context.LoadFromStream(ms);
                assembly.EntryPoint.Invoke(null, new object[] { new string[] { "arg1", "arg2", "etc" } });

            }
        }
    }
}

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

    }
}

0 / 0 / 0

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

Сообщений: 7

1

03.03.2019, 22:27. Показов 13926. Ответов 11


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

Код

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 минут
Если я прописываю два класса в одном файле то все хорошо, а если по разным то вот такие ошибки, может кто сказать как линкануть файл? Указать его вначале? Подключить? Я думал что если все одним проектом то таких проблем быть не должно, но видимо ошибся

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



  • Remove From My Forums
  • Question

  • User397255882 posted

    My asp.net page runs fine in VWD Express 2010 but on the server i get this error:

    error CS0103: The name 'DropDownList_Nodes' does not exist in the current context
    If anyone can help me I would appreciate it.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace OrionNodeEvent
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {     
                if (!this.IsPostBack)//only do on 1st page load
                {
                    FillListBox();
                }            
            }//end Page_Load
    
            protected void Submit_Click(object sender, EventArgs e)
            {
                string connectionString = @"data source=****;initial catalog=****;user id=*****;" +
                        "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes";            
                string insertSQL;
                DateTime currentTime = DateTime.UtcNow; 
                insertSQL = @"USE **** INSERT INTO ***** (";
                insertSQL += "Node_Name, Event, Solution, Time) ";
                insertSQL += "VALUES ('";            
                insertSQL += DropDownList_Nodes.SelectedItem.ToString()  + "', '";
                insertSQL += TextBox_Event.Text + "', '";
                insertSQL += TextBox_Solution.Text + "', '";
                insertSQL += currentTime + "')";
    
                SqlConnection sql_connection = new SqlConnection(connectionString);
                SqlCommand sql_command = new SqlCommand(insertSQL, sql_connection);
    
                int added = 0;//counter for rows inserted to DB
                try
                {                
                    sql_connection.Open();
                    added = sql_command.ExecuteNonQuery();
                    Label_Info.Text = added.ToString() + " records inserted.";
                }
                catch(Exception error)
                {
                    Label_Info.Text = error.Message;                
                }
                finally
                {
                    sql_connection.Close();
                    sql_connection.Dispose();
                }
                 
            }//end Submit_Click
            protected void FillListBox()
            {
                string connectionString = @"data source=****;initial catalog=****;user id=****;" +
                        "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes";
                
                DropDownList_Nodes.Items.Clear();
                string selectSQL = @"USE **** SELECT ***, *** FROM *** ORDER BY ***";
    
                SqlConnection sql_connection = new SqlConnection(connectionString);
                SqlCommand sql_command = new SqlCommand(selectSQL, sql_connection);
                SqlDataReader sql_reader;
                  try
                {                
                    sql_connection.Open();
                    sql_reader = sql_command.ExecuteReader();
                    while (sql_reader.Read())
                    {
                        ListItem newitem = new ListItem();
                        newitem.Text = sql_reader["****"].ToString();
                        newitem.Value = sql_reader["****"].ToString();
                        DropDownList_Nodes.Items.Add(newitem);
                    }//end while
                    sql_reader.Close();
                    sql_reader.Dispose();
                }//end try
                catch(Exception error)
                {
                    Label_Info.Text = error.Message;               
                }
                finally
                {
                    sql_connection.Close();
                    sql_connection.Dispose();
                }
            }//end FillListBox
      	public override void VerifyRenderingInServerForm(Control control)
            {
                return;
            }
        }//end public partial class _Default : System.Web.UI.Page
    }//end namespace OrionNodeEvent
    
    // ASP PAGE ***************************************
    
    <%@  Language="C#"  AutoEventWireup="true"
        CodeBehind="OrionNodeEvent.aspx.cs" Inherits="OrionNodeEvent._Default" Src="OrionNodeEvent.aspx.cs" %>    
    
        <html>
        <head>
        <title>Orionz</title>
        </head>
        <body>
    
        <h2>Select a Node to add an event and resolution.</h2>   
        <p><asp:DropDownList ID="DropDownList_Nodes" runat="server"></asp:DropDownList></p>
       <p><strong>Event</strong><asp:TextBox ID="TextBox_Event" runat="server" style="margin-left: 25px" 
                Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox></p>
       <p><strong>Solution</strong><asp:TextBox ID="TextBox_Solution" runat="server" 
                style="margin-left: 10px" Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox> </p>         
       <p><asp:Button ID="Button_Submit" runat="server" Text="Submit" OnClick="Submit_Click"/></p>
        <p><asp:Label ID="Label_Info" runat="server" Text="" ></asp:Label> </p>
        </body>
        </html>
    
    

Answers

  • User397255882 posted

    SOLVED:

    Added these control statements to the Default.aspx.cs:

    protected global::System.Web.UI.HtmlControls.HtmlForm form1;
    protected System.Web.UI.WebControls.Label Label_Info; 
    protected System.Web.UI.WebControls.DropDownList DropDownList_Nodes;
    protected System.Web.UI.WebControls.TextBox TextBox_Event;
    protected System.Web.UI.WebControls.TextBox TextBox_Solution;
    protected System.Web.UI.WebControls.Button Button_Submit;

    The server was ignoring the designer file.

    Now it loads!

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

Скрипт не работает

Скрипт не работает

Вот такой простенький скрипт но консоль выдает данную ошибку=Assets/M2.cs(8,20): error CS0103: The name `col’ does not exist in the current context
И еще желтую ошибку=Assets/M2.cs(10,28): warning CS0219: The variable `rotationY’ is assigned but its value is never used

Используется csharp

using System.Collections;

public class Moving2 : MonoBehaviour {

       
        void Update ()
        {          
                if(col.gameObject.name == «RollerBall»)
                {
                Quaternion rotationY = Quaternion.AngleAxis (180, Vector3.up);

                       
                }
        }
}

developers
UNец
 
Сообщения: 15
Зарегистрирован: 30 янв 2016, 22:55

Re: Скрипт не работает

Сообщение Smouk 03 мар 2016, 10:36

1. Из этого не понять в чем именно ошибка. Где объявлено col и зачем? Для получения имени объекта если скрипт висит на нем это не нужно.
В принципе не очень верно каждый update без необходимости сравнивать текст. Лучше при создании объекта использовать флаг или int с типом объекта, например.
2. Если перевести там прямо написано, что переменная rotationY никогда не используется.

Последний раз редактировалось Smouk 03 мар 2016, 10:39, всего редактировалось 2 раз(а).

Smouk
UNIт
 
Сообщения: 146
Зарегистрирован: 16 сен 2009, 08:47

Re: Скрипт не работает

Сообщение BladeBloodShot 03 мар 2016, 10:38

Ну так переведи ошибки, нет определения col то бишь надо public var col = там чему то;

BladeBloodShot
UNец
 
Сообщения: 38
Зарегистрирован: 03 фев 2016, 22:31



Re: Скрипт не работает

Сообщение developers 03 мар 2016, 12:06

А насчет 2 причины

developers
UNец
 
Сообщения: 15
Зарегистрирован: 30 янв 2016, 22:55

Re: Скрипт не работает

Сообщение iLLoren 03 мар 2016, 13:59

developers писал(а):А насчет 2 причины

Научись разбираться с мелочами самостоятельно, тебе самому то не стыдно что имея видео о том как с 0 сделать всё правильно ты косячишь и вместо пересмотров урока ты плачешь на форуме о проблемах которые сам можешь легко решить?

Аватара пользователя
iLLoren
UNIт
 
Сообщения: 103
Зарегистрирован: 31 дек 2015, 12:00

Re: Скрипт не работает

Сообщение Tolking 03 мар 2016, 14:16

Желтая ошибка называется предупреждением и в переводе с английского гласит: ты нахрена опредилил переменную `rotationY’ если нигде ее не используешь!

Таки да!!! Английский знать надо или пользоваться переводчиком…

Ковчег построил любитель, профессионалы построили Титаник.

Аватара пользователя
Tolking
Адепт
 
Сообщения: 2684
Зарегистрирован: 08 июн 2009, 18:22
Откуда: Тула


Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 6



Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

In my PlayerMovement.cs I get this error with MonoBehaviour, Animator, playerAnimator, Vector3, Rigidbody, and Qauternion. Here is a copy of my file:

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

    private Animator playerAnimator;
    private float moveHorizontal;
    private float moveVertical;
    private Vector3 movement;
    private float turningSpeed = 20f;
    private Rigidbody playerRigidbody;

    // Use this for initialization
    void Start () {

        // Gather components from the play GameObject
        playerAnimator = GetComponent<Animator> ();
        playerRigidbody = GetComponent<Rigidbody> ();

    }

    // Update is called once per frame
    void Update () {

        // Gather input from the keyboard
        moveHorizontal = Input.GetAxisRaw ("Horizontal");
        moveVertical = Input.GetAxisRaw ("Vertical");

        movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

    }

    void FixedUpdate () {

        // If the player's movement vector does not equal zero...
        if (movement != Vector3.zero) {

            // ...then create a target rotation based on the movement vecor...
            Quaternion targetRotation = Quaternion.LookRotation(movement, Vector3.up);

            // ...and create another rotation that moves from the current roatation to the target rotation...
            Quaternion newRotation = Qauternion.Lerp (playerRigidbody.rotation, targetRotation, turningSpeed * Time.deltaTime);

            // ...and change the player's rotation to thenew incremental rotation...
            playRotation.MoveRotation(newRotation);

            // ...then play the animation.
            playerAnimator.SetFloat ("Speed", 3f);
        } else {
            //Otherwise don't play the animation
            playerAnimator.SetFloat ("Speed", 0f);
        }

    }

}

Any help would be greatly appreciated. Thank you!

2 Answers

Alan Mattanó

PLUS

Go to the Console by pressing Ctrl Shift «C» or in the top menu: Windows -> Console .
The Console will show you the Error message with the file location «Assets/Path/FileName.cs»
and the line number, where is the error. In your case is can be 103 then there is a coma and the position.
If you double click the error message in the console, Unity will try to open Mono putting the cursor at the same position where is the error. It can be shown in red. The error can be not in the same line, for example if we forget to close a ;
or }. In this case look line above the error.
The console will show you more than one error probably as consequence of the first one. So if you fix the first error, the other errors messages probably will disappear.

Becky Hirsch September 15, 2015 12:24am

Great to know! Thanks again Alan! :)

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error creating session парус 10
  • Error creating remote thread code 0 advor
  • Error creating registry key hkey local machine
  • Error creating project xsrf check failed
  • Error creating process не удается найти указанный файл directx

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии