Bhupinder Singh
Bhupinder Singh

Reputation: 39

Why initializing in this way gives compile time error?

This may seem something silly but can any one tell me why the below code is giving error ?

    class Program
{
    static int abc;
    abc = 110;

    static void Main(string[] args)
    {
        Console.WriteLine(abc);
    }
}

But if I do the initialization like this, it runs !

    class Program
{
    static int abc = 110;

    static void Main(string[] args)
    {
        Console.WriteLine(abc);
    }
}

Upvotes: 3

Views: 112

Answers (2)

Submersed
Submersed

Reputation: 8870

You have to use a static initializer to do what you're wanting to do (if not just assigned inline), otherwise you need to assign it in a constructor or method.

    class Program
{
    static int abc;

    static Program(){
       abc = 110;
    }

    static void Main(string[] args)
    {
        Console.WriteLine(abc);
    }
}

Check this page for more info.

Upvotes: 2

Glenn Ferrie
Glenn Ferrie

Reputation: 10380

The line abc = 110 is not within a method body. You can initialize the variable at declaration, but you cannot have a line of code that makes that assignment outside of a method body. The class file is invalid.

Upvotes: 1

Related Questions