Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference is required?

am learning C# and have written a simple bit of code, but i don't understand why i have to declare the variables userChoice and numberR within the scope of the Main method and not within the scope of the class. If i declare it within the class like this, i get build errors

using System;

namespace FirstProgram
{
class Program
{
   string userChoice;
   int numbeR;

 static void Main()
    {
        Console.WriteLine("Write a number...");
        userChoice = Console.ReadLine();

        numbeR = Convert.ToInt32(userChoice);
        Console.WriteLine("You wrote {0}", numbeR);
        Console.ReadLine();
    }
}
}

But only this will give me no errors:

using System;

namespace FirstProgram
{
class Program
{    
 static void Main()
    {
        string userChoice;
        int numbeR; 

        Console.WriteLine("Write a number...");
        userChoice = Console.ReadLine();

        numbeR = Convert.ToInt32(userChoice);
        Console.WriteLine("You wrote {0}", numbeR);
        Console.ReadLine();
    }
}
}

Shouldn't i be able to use those two variables within Main just by declaring them in the Class like above? I am confused... thanks for any advice.

like image 971
Daniel Gratz Avatar asked Aug 02 '26 08:08

Daniel Gratz


1 Answers

You can't do it because Main() is a static function. Your variables are declared as instance variables and can only be accessed on an instance of the Program class. If you declare userChoice and numbeR as static variables, it will compile.

static string userChoice;
static int numbeR;

static void Main()
{
    //your code
}

Static members mean you can use the member without instantiating the class. Imagine:

public class MyClass
{
     public static int StaticInt;
     public int NonStaticInt;
}

means you could do:

MyClass.StaticInt = 12;  // legal
MyClass.NonStaticInt = 12; // error, can't staticly access instance member

and all classes would have access to that change, since there is only one MyClass.StaticInt in your program. To change NonStaticInt, you would have to create an instance of that class, like so:

MyClass mine = new MyClass();
mine.NonStaticInt = 12;  // legal
mine.StaticInt = 12; // Error, cannot access static member on instance class.
like image 81
Christopher Currens Avatar answered Aug 04 '26 00:08

Christopher Currens