Referring own class in C# with VS2022

Viewed 56

This might be a stupid question, but…

I am moving towards Visual Studio Community 2022 (version 17.3.3, just in case).

I create a C# console application, using the .NET 6.0 Framework, and create a new class ‘Foo’ by right-clicking the project and selecting Add -> Class. The IDE generates an internal class Foo (let us leave it empty for simplicity). I then add in the Program.cs file a declaration of an object of my new class, like:

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

Foo F = new Foo();

The issue is that this simple code generates a CS0246 compile error (“Foo not found”).

Of course, I can add a using directive at the beginning of Program.cs, but:

  • As a teacher in charge of an introductory programming class, I like to start from the basics: this forces me to introduce using directives even before giving an intuition of what a class is. I know .NET has not been designed for teaching purposes, yet…
  • From what I read, VS 2022 wanted to improve productivity, by avoiding the need to have 10 lines of code before being able to perform the slightest action, and moving to something closer to Python instead. How is this goal helped by not including the project’s own namespace in the default using directives ?!?

Am I missing something here?

1 Answers

What you're missing is that you don't need to put your Foo class in a namespace.

In your "Foo.cs" file you can put just this (note the lack of a namespace):

class Foo
{
    // Whatever
}

Then in your "Program.cs" you can put this, and it will compile OK:

Foo foo = new Foo();
Console.WriteLine("Hello, World!");

It's bad practice to not use a namespace, but that can be for a later lesson.

Related