Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# code not present inside namespace and class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading