Add a class to a console app?

Maylar

Member
Joined
Jan 22, 2021
Messages
18
Programming Experience
10+
I'm trying to create a console application with C# and there's something that I obviously don't understand. I've added a class file (.cs) and put one method in it but I can't seem to reference it from the main function in the Program class. The class name is Class1. I can't instantiate a Class1 object instance. Why not?

C#:
namespace ConsoleApp1
{
    class Program
    {
        Class1 Tasks;

        static void Main(string[] args)
        {
            int retval = 0;
            int pause = 0;

            Tasks = new Class1(); // an error here, object reference.
        }
    }
}
 
CS0120 An object reference is required for the non-static field, method, or property 'Program.Tasks'
Tasks field is non-static and can't be set without an instance of Program class (think p=new Program() > p.Tasks can be set), instead make the field static as well.
 
For future reference, if an error occurs, ALWAYS provide the error message. The issue was obvious to the experienced eye in this case but that will not always be the case. The error message is provided for a reason. If you'd like us to diagnose the issue, provide us with the diagnostic information provided to you.
 
It could also be worth mentioning that since Main is static inside Program class, the code there does not have access to any instance of Program class, this keyword is not valid in static members.
 

Latest posts

Back
Top Bottom