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

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Introduction

Hello fellow developers! I want to talk to you today about a C# compiler error that you might have encountered before: CS0103. This error message can be confusing and frustrating, especially if you’re a beginner, but don’t worry! With a little bit of understanding and some practical examples, you’ll be able to fix this error in no time.

What is the CS0103 Error?

The full error message for CS0103 typically looks like this:

CS0103: The name 'identifier' does not exist in the current context

Reasons for the CS0103 Error

Essentially, what this error means is that you are trying to use a variable, method, or class that the compiler cannot find or does not recognize. There are a few reasons why this error might occur:

  • You misspelled the name of the identifier.
  • The identifier is out of scope, meaning that it’s defined in a different file, class, or method.
  • You haven’t declared the identifier yet, or you declared it incorrectly.

Let’s take a look at some examples of how this error can occur and how to fix it.

Example 1: Misspelled Identifier

string message = "Hello, world!";
Console.WriteLine(mesage); // CS0103 error

In this example, we have misspelled the name of the message variable when we tried to use it in the Console.WriteLine() method. To fix this error, we simply need to correct the spelling of the variable:

string message = "Hello, world!";
Console.WriteLine(message); // Fixed!

Example 2: Out of Scope Identifier

class MyClass
{
    string message = "Hello, world!";
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(MyClass.message); // CS0103 error
    }
}

In this example, we are trying to access the message variable that is defined in the MyClass class. However, since message is not a static member of MyClass, we need to create an instance of the class in order to access it. Here’s how we can fix this error:

class MyClass
{
    public string message = "Hello, world!";
}

class Program
{
    static void Main(string[] args)
    {
        MyClass myObj = new MyClass();
        Console.WriteLine(myObj.message); // Fixed!
    }
}

Example 3: Undeclared Identifier

class Program
{
    static void Main(string[] args)
    {
        int sum = x + y; // CS0103 error
        Console.WriteLine(sum);
    }
}

In this example, we are trying to use two variables, x and y, in order to calculate the sum. However, we haven’t declared these variables anywhere in our code. To fix this error, we need to declare the variables before we try to use them:

class Program
{
    static void Main(string[] args)
    {
        int x = 3;
        int y = 5;
        int sum = x + y;
        Console.WriteLine(sum); // Fixed!
    }
}

Conclusion to Error CS0103

In conclusion, CS0103 is a common compiler error that can occur when you’re trying to use a variable, method, or class that the compiler cannot find or does not recognize.

To fix this error, make sure that you’ve spelled your identifiers correctly, that they’re in scope, and that you’ve declared them before you try to use them.

I hope this article has been helpful in understanding CS0103 and how to resolve it in C# code. Happy coding!

Только сегодня начал изучать 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 бронзовых знака

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

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

Код

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

  • Remove From My Forums
  • Question

  • User1201429566 posted

    Hello everyone, I am not sure why am I getting the name ‘listID’ does now exist in the current context. As I am still new to ASP.NET, any help would be greatly appreciated! Thanks!

    
    
    
    my aspx.cs file
    
    
    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;
    using System.Configuration;
    
    
    namespace CustomerHandyApplication
    {
    public partial class ServiceView : System.Web.UI.Page
    {
    // create a new class by initializing service
    ServiceInfo aService = new ServiceInfo();
    ServiceInfo bService = new ServiceInfo();
    ServiceInfo list = new ServiceInfo();
    
    
    protected void Page_Load(object sender, EventArgs e)
    {
    // create instance where ServiceInfo = a
    ServiceInfo a = new ServiceInfo();
    List listingsService = new List ();
    
    
    if (!IsPostBack)
    {
    //store the list of ServiceNo into the nameList
    List nameList = a.getListingNameAll();
    List handyService = listingsService;
    }
    }
    
    
    // bind the details in the grid view together
    // create a new class ServiceList
    protected void bind()
    {
    List serviceData = new List();
    serviceData = aService.getServiceInfoAll();
    gvService.DataSource = serviceData;
    gvService.DataBind();
    
    
    List serviceList = new List();
    serviceList = bService.getListingNameAll();
    gvService.DataSource = serviceList;
    gvService.DataBind();
    
    
    List listingsService = new List();
    listingsService = list.getListings(listID);
    gvService.DataSource = listingsService;
    gvService.DataBind();
    }
    
    
    protected void gvService_SelectedIndexChanged(object sender, EventArgs e)
    {
    // Get the currently selected row
    // Display by the row
    GridViewRow row = gvService.SelectedRow;
    
    
    // Get Listing_Name from the selected row,
    // which is the first row, i.e. index 0
    string listName = row.Cells[0].Text;
    decimal price = decimal.Parse(row.Cells[1].Text);
    string handyName = row.Cells[2].Text;
    
    
    Response.Redirect("Pre-BookAppointment.aspx");
    }
    
    
    protected void ddl_List_SelectedIndexChanged(object sender, EventArgs e)
    {
    string listID = ddl_List.SelectedValue;
    Response.Redirect("ViewService.aspx?ListID=" + listID);
    bind();
    }
    }
    }
    
    
    //my cs file:
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Data;
    
    
    namespace CustomerHandyApplication
    {
    public class ServiceInfo
    {
    //Private string _connStr = Properties.Settings.Default.DBConnStr;
    // set the values to each of the attributes
    //System.Configuration.ConnectionStringSettings _connStr;
    string _connStr = ConfigurationManager.ConnectionStrings["CustomerContext"].ConnectionString;
    
    
    // private attributes of attributes in the database table
    private string _listID = "";
    private string _listName = "";
    private decimal _price = 0;
    private string _handyName = "";
    
    
    
    
    // Default constructor
    public ServiceInfo()
    {
    }
    
    
    // Constructor that take in all data required to build a ServiceInfo object
    // ServiceInfo class that takes 3 arguments
    // set the attributes to each of the variables by making it private
    public ServiceInfo(string listID, string listName, decimal price, string handyName)
    {
    _listID = listID;
    _listName = listName;
    _price = price;
    _handyName = handyName;
    }
    
    
    // Constructor that take in all except Listing_ID
    // create all variables as the attributes
    // ID – unique key of service = Listing_ID
    // auto constructor: it generates an auto listName from the database to access to all the attributes of the ServiceInfo table.
    // Hence it does not pass in the service_No, but the rest of the attributes in the table unless it is specified by the rules of the company.
    
    
    public ServiceInfo(string listName, decimal price, string handyName)
    : this("", "", price, handyName)
    {
    }
    
    
    // Constructor that take in only Listing_ID. The other attributes will be set to 0 or empty.
    public ServiceInfo(string listID)
    : this(listID, "", 0, "")
    {
    }
    
    
    // set the attributes under the object
    // by creating the class instances of each attributes in the object
    // create the Get/Set the attributes of the Product object.
    // Note the attribute name (e.g. Listing_Name) is same as the actual database field name.
    // This is for ease of referencing.
    
    
    public string Listing_ID
    {
    get
    {
    return _listID;
    }
    set
    {
    _listID = value;
    }
    }
    
    
    public string Listing_Name
    {
    get
    {
    return _listName;
    }
    set
    {
    _listName = value;
    }
    }
    
    
    public decimal Price
    {
    get
    {
    return _price;
    }
    set
    {
    _price = value;
    }
    }
    
    
    public string Handyman_Name
    {
    get
    {
    return _handyName;
    }
    set
    {
    _handyName = value;
    }
    }
    
    
    //Below as the Class methods for some DB operations.
    // getServiceInfo(Listing_Name) - to retrieve listName data from the gvService
    public ServiceInfo getSeviceInfo(string listID)
    {
    ServiceInfo handylistDetail = null;
    string list_Name,handy_Name;
    decimal price;
    
    
    // query the attributes by selecting each of the attributes in the CustomerContext database
    string queryStr = "SELECT * FROM Lisitngs WHERE Listing_ID = @ListID ";
    
    
    // request the connection by getting the database of the attributes from the CustomerContext database using the connStr variable
    SqlConnection conn = new SqlConnection(_connStr);
    SqlCommand cmd = new SqlCommand(queryStr, conn);
    cmd.Parameters.AddWithValue("@ListID", listID);
    
    
    // open the connection by starting to read and execute each of the attibutes in the CustomerContext database
    conn.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    
    
    // read each of the attributes in the CustomerContext in the string format
    // exclude listID which is primary key
    if (dr.Read())
    {
    list_Name = dr["Listing_Name"].ToString();
    price = decimal.Parse(dr["Price"].ToString());
    handy_Name = dr["Handyman_Name"].ToString();
    
    
    handylistDetail = new ServiceInfo(listID, list_Name, price, handy_Name);
    }
    else
    {
    handylistDetail = null;
    }
    
    
    conn.Close();
    dr.Close();
    dr.Dispose();
    
    
    return handylistDetail;
    } //end of retrieve
    
    
    // getServiceInfoAll()-to retrieve all the data from the gvService
    public List getServiceInfoAll()
    {
    List handyList = new List();
    
    
    // include listName which is a primary key
    string list_ID, list_Name, handy_Name;
    decimal price;
    
    
    string queryStr = "SELECT * FROM Listings";
    
    
    SqlConnection conn = new SqlConnection(_connStr);
    SqlCommand cmd = new SqlCommand(queryStr, conn);
    
    
    conn.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    
    
    // include listName which is a primary key
    while (dr.Read())
    {
    list_ID = dr["Listing_ID"].ToString();
    list_Name = dr["Listing_Name"].ToString();
    price = decimal.Parse(dr["Price"].ToString());
    handy_Name = dr["Handyman_Name"].ToString();
    
    
    ServiceInfo a = new ServiceInfo(list_ID, list_Name, price, handy_Name);
    handyList.Add(a);
    }
    
    
    conn.Close();
    dr.Close();
    dr.Dispose();
    
    
    return handyList;
    }
    
    
    //getListingNameAll() - to retrieve all the data from the ddl_List
    public List getListingNameAll()
    {
    List nameList = new List();
    
    
    string list_ID, list_Name, handy_Name;
    decimal price;
    
    
    string queryStr = "SELECT * FROM Listings";
    
    
    SqlConnection conn = new SqlConnection(_connStr);
    SqlCommand cmd = new SqlCommand(queryStr, conn);
    
    
    conn.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    
    
    // include listID and servNo which are primary keys
    while (dr.Read())
    {
    list_ID = dr["Listing_ID"].ToString();
    list_Name = dr["Listing_Name"].ToString();
    price = decimal.Parse(dr["Price"].ToString());
    handy_Name = dr["Handyman_Name"].ToString();
    
    
    ServiceInfo a = new ServiceInfo(list_ID, list_Name, price, handy_Name);
    nameList.Add(a);
    }
    
    
    conn.Close();
    dr.Close();
    dr.Dispose();
    
    
    return nameList;
    }
    
    
    
    
    //getListings() - to get the listID from the ddl_List
    public ServiceInfo getListings(string listID)
    {
    ServiceInfo handyService = null;
    string list_Name, handy_Name;
    decimal price;
    
    
    // query the attributes by selecting each of the attributes in the CustomerContext database
    string queryStr = "SELECT * FROM Lisitngs WHERE Listing_ID = @ListID ";
    
    
    // request the connection by getting the database of the attributes from the CustomerContext database using the connStr variable
    SqlConnection conn = new SqlConnection(_connStr);
    SqlCommand cmd = new SqlCommand(queryStr, conn);
    cmd.Parameters.AddWithValue("@ListID", listID);
    
    
    // open the connection by starting to read and execute each of the attibutes in the CustomerContext database
    conn.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    
    
    // read each of the attributes in the CustomerContext in the string format
    // exclude listID which is primary key
    if (dr.Read())
    {
    list_Name = dr["Listing_ID"].ToString();
    price = decimal.Parse(dr["Price"].ToString());
    handy_Name = dr["Handyman_Name"].ToString();
    
    
    handyService = new ServiceInfo(listID, list_Name, price, handy_Name);
    }
    else
    {
    handyService = null;
    }
    
    
    conn.Close();
    dr.Close();
    dr.Dispose();
    
    
    return handyService;
    } //end of retrieve

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

Интересное по теме:

  • Ошибка кода 5100 основной шлюз указан неверно
  • Ошибка компас ошибка при направлении команды приложению
  • Ошибка компилятора cs0029
  • Ошибка компилятора c3861
  • Ошибка кода 5022 tp link

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: