Home > OS >  Code not present inside namespace and class
Code not present inside namespace and class

Time:10-26

I am learning C# and came across a sample code which are as follows :

Shapes.cs

using System;

public record Position(int X, int Y);

public record Size(int Width, int Height);

public abstract record Shape(Position Position, Size Size)
{
    public void Draw() => DisplayShape();

    protected virtual void DisplayShape()
    {
        Console.WriteLine($"Shape with {Position} and {Size}");
    }
}

ConcreteShapes.cs

using System;

public record Rectangle(Position Position, Size Size) : Shape(Position, Size)
{
    protected override void DisplayShape()
    {
        Console.WriteLine($"Rectangle at position {Position} with size {Size}");
    }
}

public record Ellipse(Position Position, Size Size) : Shape(Position, Size)
{
    protected override void DisplayShape()
    {
        Console.WriteLine($"Ellipse at position {Position} with size {Size}");
    }
}

Program.cs

Rectangle r1 = new(new Position(33, 22), new Size(200, 100));
Rectangle r2 = r1 with { Position = new Position(100, 22) };
Ellipse e1 = new(new Position(122, 200), new Size(40, 20));

DisplayShapes(r1, r2, e1);

void DisplayShapes(params Shape[] shapes)
{
    foreach (var shape in shapes)
    {
        shape.Draw();
    }
}

Project structure :

enter image description here

Question :

When I build the project and run the the project with the below command :

dotnet run --project .\RecordsInheritance\RecordsInheritance.csproj

I am getting output which i.e. DisplayShapes method is getting called and output is displayed. The C# code in Program.cs is not wrapped inside a namespace and a class and yet it is getting executed correctly like a javascript code. Can someone explain me how this code is getting executed correctly as the code is not wrapped inside a class and there is no public static method as well ?

CodePudding user response:

This is a new feature in Visual Studio 2022 and .NET 6 SDK >

Top Level Statements

It is a simplified way to express the entry point of your applications.

In other words is a new way of writing the Program.cs class.

According to Microsoft

Top-level statements enable you to avoid the extra ceremony required

when writing your entry point.

CodePudding user response:

Recent version of C# and .NET has few enhancements that you see:

  • file scoped namespces, that allow to write
namespace MyProject;
// All below does not need braces and indentation, it goes to above namespace
public class ......
  • due to that, template for console app could be simplified and now body of the file is just what would be places inside Main method, thus it gets executed and you don't need anthing execpt compiling code there

Further reading
File scoped namespaces
New Console App template

  • Related