Since the .NET version has been updated, there is no need to write entire C# code just to print 'Hello World!'. Just Console.WriteLine();
is enough. But what I could not understand, is how to define a new function outside Main()
?
If I want to develop a separate function outside Main()
, do I need to write entire code including using System;
and namespaces and Main()
function? I am talking about updated version which is C# v10.
Please, do enlighten me!
I hope this question is not much lengthy and you got idea regarding the problem.
CodePudding user response:
There are two important things to understand here:
Firstly, top-level statements and implicit using directives are entirely different features. So you can declare a class as normal, but still omit the using directives. Likewise if you don't want to declare a namespace, you don't have to - although these days you could just use a file-scoped namespace declaration, e.g. namespace MyNamespace;
without indenting everything.
Secondly, even with top-level statements, you can write methods... but they're effectively local methods within the Main
method, and come with all the restrictions that imposes (e.g. no overloading). Note that even with top-level statements for your entry point, you can still declare other classes elsewhere - it would be entirely reasonable to have a brief Program.cs
using top-level statements just to get everything going, but use "regular" C# elsewhere in the project. Indeed, that's how the ASP.NET Core templates work these days.
CodePudding user response:
You can write that like a normal method.
using System;
Console.WriteLine("Hello World");
display();
static void display()
{
Console.WriteLine("from display");
}