• Register
262 points
‚óŹ3

In C#, the term 'identifier' refers to the name of  all type and type members. In short every name of any namespace, class, struct, delegate, enum, constant, local variable, object, property, method, filed etc. are considered as identifiers. To access a value or instance referance, we must have to use identifiers. Sometimes we need to decorate source code in various scope and encapsulated blocks. When an identifier is declared but inaccesable from another scope from where we try to access it, then it causes the name not exist error.

Explanation of the problem

In Microsoft .NET language reference marked "The name 'identifier' does not exist in the current context" under the title "Compiler Error CS0103”. I means an attempt was made to use an identifier that does not exist in the class, namespace, or scope. To make sure that the name that you are trying to use is available, check the spelling of the name and check your using directives and assembly references.

This error frequently occurs when you declare a variable inside a loop or a try or if block and then attempt to access it from an enclosing code block or a separate code block. It often can be generated if you try to access a static member from an object instance or an instance member without creating an instance.

using System;

class MyClass
{
    public static void Main()
    {
        try
        {
            // The following declaration is only available inside the try block.
            var conn = new MyClass();
        }
        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);
        }
    }
}

 

Solution of the problem

First of all check your pre-porcessing statements (if any) where you include reference namespaces by using keyword. Then you have to move declaration in appropriate scope so that it can be accessable from where we try to access it. Or if causes static and instance problem, please check your source definitions so that you defiened static fileds/members and instance fields/members appropriately.

To resolve the error in the example, the first step is to move the declaration of conn out of the try block. The following expression no longer causes an error, because the declaration of conn is in scope.

using System;

class MyClassA
{
    public static void Main()
    {
        // declaration is available throughout the Main method.
        MyClassA conn = null;
        try
        {
            // Inside the try block, use the conn variable that you declared previously.
            conn = new MyClassA();
        }
        catch (Exception e)
        {
            if (conn != null)
                Console.WriteLine("{0}", e);
        }
    }
}