Меню

Ошибка cs0103 visual studio

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

  • 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

Asked
4 years, 1 month ago

Viewed
5k times

I am working on a project that creates a simple perimeter and area calculator based on the values the user inputs. (For finding window perimeter and glass area). However, I’m stuck with 4 errors… all of which are CS0103. Can anyone help me fix these errors or clean up my code. I’m trying to separate everything into methods so I would like to keep the code in that general format.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            double totalLength, totalWidth, windowPerimeter, glassArea;

            //display instructions
            DisplayInstructions();

            // ask for width
            totalWidth = AskDimension();

            //ask for lenght
            totalLength = AskDimension();

            // calculate window Perimeter
            windowPerimeter = (2 * totalWidth) * (2 * totalLength);

            //calculate the area of the window & display output
            glassArea = totalWidth * totalLength;

            //calculate and display outputs

            Console.WriteLine("the lenth of the wood is " + windowPerimeter + " feet");
            Console.WriteLine("the area of the glass is " + glassArea + " square feet");
            Console.ReadKey();

            Console.ReadKey();
        }

        //display instructions
        public static void DisplayInstructions()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("This app will help you calculate the amount of wood and glass needed for your new windows!");
            Console.WriteLine("   ");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("*Note* Please enter a height/width value between 0.01 - 100, all other values will cause a system error.");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("   ");
        }

        //ask for width
        public static double AskDimension()
        {
            double totalWidth;
            const double MAX_HEIGHT = 100.0;
            const double MIN_Height = 0.01;
            string widthString;
            Console.WriteLine("please enter your height of the window");
            widthString = Console.ReadLine();
            totalWidth = double.Parse(widthString);
            if (totalWidth < MIN_Height)
            {
                Console.WriteLine("you enter vaule less than min width n" + "using minimum one");
                totalWidth = MIN_Height;
            }
            if (totalWidth > MAX_HEIGHT)
            {
                Console.WriteLine("you enter value grater than Max heightn" + "using maximum one");
                totalWidth = MAX_HEIGHT;
            }

            return AskDimension();
        }

        //ask for height
        public static double AskDimension(string dimension)
        {
            double totalLength;
            const double MAX_HEIGHT = 100.0;
            const double MIN_Height = 0.01;
            string heightString;
            Console.WriteLine("please enter your height of the window");
            heightString = Console.ReadLine();
            totalLength = double.Parse(heightString);
            if (totalLength < MIN_Height)
            {
                Console.WriteLine("you enter vaule less than min width n" + "using minimum one");
                totalLength = MIN_Height;
            }
            if (totalLength > MAX_HEIGHT)
            {
                Console.WriteLine("you enter value grater than Max heightn" + "using maximum one");
                totalLength = MAX_HEIGHT;
            }

            return AskDimension();
        }
        //calculate and display outputs
        public static double AskDimesnion(string windowPerimeter,
                                          string glassArea,
                                          string widthString,
                                          string heightString)

        {

            windowPerimeter = 2 * (totalWidth + totalLength);
            glassArea = (totalWidth * totalLength);
            Console.WriteLine("the lenth of the wood is " + windowPerimeter + " feet");
            Console.WriteLine("the area of the glass is " + glassArea + " square feet");
            Console.ReadKey();
            return AskDimension();
        }
}
}

Screenshot of errors in the method:
Screenshot of errors in the method

dymanoid's user avatar

dymanoid

14.5k4 gold badges38 silver badges63 bronze badges

asked Dec 11, 2018 at 16:30

7

Your totalWidth variable is not defined anywhere in your scope. It should be defined somewhere. Depending on where you exactly want to define it, you can do it internally in your AskDimension method or more globally. It seem by your logic it should be an input parameter of your method. Also you have other errors in your code. Your method is called AskDimesnion but you are calling it in your code by AskDimension (hopefully the correct method name…)

For variable scope, you can check Microsoft’s own documentation

answered Dec 11, 2018 at 16:36

Alfredo A.'s user avatar

Alfredo A.Alfredo A.

1,6572 gold badges31 silver badges43 bronze badges

1

The initial problem was that your variables weren’t class scoped and also the calculations seem a bit crazy to me. But from pasting your code in to my editor I’ve had a quick tidy up and come out with the following:

using System;

namespace TestConsoleApplication
{
    class Program
    {
        static double _totalLength, _totalWidth, _windowPerimeter, _glassArea;

        static void Main(string[] args)
        {
            DisplayInstructions();
            _totalWidth = AskDimension("Height");
            _totalLength = AskDimension("Width");
            _windowPerimeter = (2 * _totalWidth) + (2 * _totalLength);
            _glassArea = _totalWidth * _totalLength;
            Console.WriteLine("The length of the wood is " + _windowPerimeter + " feet");
            Console.WriteLine("The area of the glass is " + _glassArea + " square feet");
            Console.ReadKey();
        }

        private static void DisplayInstructions()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("This app will help you calculate the amount of wood and glass needed for your new windows!");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("*Note* Please enter a height/width value between 0.01 - 100, all other values will cause a system error.");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine();
        }

        private static double AskDimension(string dimensionType)
        {
            const double maxDimension = 100.0;
            const double minDimension = 0.01;

            Console.WriteLine($"Please enter your {dimensionType} of the window");

            var dimensionString = Console.ReadLine();
            var dimension = double.Parse(dimensionString);

            if (dimension < minDimension)
            {
                DisplayDimensionErrorAndExit("Min");
            }
            else if (dimension > maxDimension)
            {
                DisplayDimensionErrorAndExit("Max");
            }

            return dimension;
        }

        private static void DisplayDimensionErrorAndExit(string dimensionToShow)
        {
            Console.WriteLine($"You entered a value less than {dimensionToShow} dimension");
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            Environment.Exit(0);
        }
    }
}

If a user enters invalid input the program will terminate, apart from that the calculations work and the correct output displayed.
If you’ve got any questions about it at all just ask me 🙂

answered Dec 11, 2018 at 17:01

Coops's user avatar

CoopsCoops

2613 silver badges7 bronze badges

2

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

    }
}

  • Remove From My Forums
  • Question

  • 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.

Answers

  • 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.

    • Edited by

      Saturday, August 22, 2015 10:55 AM

    • Marked as answer by
      levens2m
      Saturday, August 22, 2015 10:56 AM

  • Remove From My Forums
  • Question

  • 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.

Answers

  • 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.

    • Edited by

      Saturday, August 22, 2015 10:55 AM

    • Marked as answer by
      levens2m
      Saturday, August 22, 2015 10:56 AM

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

  • Hello,

    I have created a very simple SSIS Package with only one component.

    Script task which has below code in Main method

    public void Main()
            {
                // TODO: Add your code here
                string name = «ABC»;
                name = name + » XYZ»;
                Dts.TaskResult = (int)ScriptResults.Success;
            }

    When I try to debug the script task, and when I hover the mouse on the variable «name» nothing appears in a tiptop.

    When I say Quick watch by selecting this variable , it display above error.

    Error in Quick watch window is

    error CS0103: The name ‘name’ does not exist in the current context   

    How can i see the values of the variables any help is appreciated.

    • Изменено

      3 апреля 2016 г. 14:47

Ответы

  • Hi Desh200,

    I was testing in Visual studio 2015 as well.

    What happens if debugging in a C# project?

    If the error still persists, you can post it in the
    visual studio forum. If the error only happens in a script task in an SSIS project, you can post it in the

    SQL Server data tools forum.

    You would get more appropriate response there.

    By the way, since the SSDT for Visual Studio 2015 is still a preview version, it is not recommended to use it in your development work.


    Eric Zhang
    TechNet Community Support

    • Предложено в качестве ответа
      HoroChan
      19 апреля 2016 г. 9:25
    • Помечено в качестве ответа
      Eric__Zhang
      24 апреля 2016 г. 10:19

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

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка crc неверный пароль
  • Ошибка cs0021 не удается применить индексирование через к выражению типа int