In this tutorial, we will learn how to write a simple “Hello World!” program in C#. This will get you familiar with the basic syntax and requirements of a C# program.
The “Hello World!” program is often the first program we see when we dive into a new language. It simply prints Hello World! on the output screen
he purpose of this program is to get us familiar with the basic syntax and requirements of a programming language.
“Hello World”
using System;
namespace HelloWorld
{
class Hello {
static void Main(string[] args)
{
//Hello comment block
Console.WriteLine("Hello World!");
}
}
}
Note: This is the default setup when creating a new application within the request solution.
Now you may run the application, press F5 and the output should be: “Hello World!”
Understanding the “Hello World” program and how it works
- //Hello comment block
- // – represents the start of a comment section in C#. No worries comment sections/blocks are not executed by the C# compiler. (Consider when reading or using comments for better communicating with developers. To learn more about comments)
- namespace HelloWorld {…}
- is used to define the application namespace. So the example above namespace is called “HelloWorld”
- the perfect way to see namespace is like a container that will consist of methods, classes, and even other namespaces. (To learn more about namespace)
- class Hello {…}
- reflecting on the above example the class is created with the name – Hello in C#. C# is an object-oriented language and is mandatory for program execution.
- static void Main(string[], args){…}
- ‘Main()‘ this a method within the class of “Hello”. During the execution of a C# application, it will start with the ‘Main()‘
- Console.WriteLine(“Hello World”);
- to keep it short just remember in console application this will print the text to the user screen.
Tackling Hello World differently
// Hello World! program
namespace HelloWorld
{
class Hello {
static void Main(string[] args)
{
System.Console.WriteLine("Hello World!");
}
}
}
The above code is another way to execute the ‘Hello World’ program. Please take note with the two codes, the orignal code we began with and the code from above, the first difference is the missing “using System;”. Second difference to notice is the adding of the “System” before Console.WriteLine
Don’t worry more on this is another post.
Take away
- ‘Main()’ method must be inside the class definition
- Every C# program has to have a class definition
- Most importantly the execution begins within the ‘Main()’ method
So let’s keep it simple as a newbie this is an excellent introduction to C#. If anything within this post is hard to comprehend, don’t worry in the beginning I was the same way as well. As you progress with your read and research everything will begin to fall in place.