Now you have the basic knowledge of C# and history of C#, so we will take a look on how to create first program of C#, and I will also explain the code, line by line.
So in this example, we will create program to print "Hello World" in C#.
You will need a Visual Studio, you can download the setup program file from official Microsoft website https://visualstudio.microsoft.com/downloads/ or you also download the ISO links of Visual Studio
If none of the above options works for you and you want to get started quickly, you can use online .NET Editor.
Let's begin creating "Hello World" program in Visual Studio 2017 Community Version ( Community version is available for free to use for individual developers and students).
If you have Visual Studio, you will be creating this application as a Console Application.
So, open your Visual Studio, select "File"->"New"->"Project"
Now, in the Next dialog box, Select "Windows Classic Dekstop" from left pane and "Console App (.NET Framework)" from right pane, provide a name to project "HelloWorldApp", change location to save project (if needed) and click "OK"
In the Program.cs
, which is opned by Default use the code below
using System;
namespace HelloWorldApp
{
class HelloWorldApp
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
}
Now, let's understand the above code:
WriteLine()
method of the Console class. The class represents the standard input, output, and error streams for console applications. Note that Console class is part of the System namespace. This line was the reason to import the namespace with the using System;
statement. If we didn't use the statement, we would have to use the fully qualified name of the WriteLine()
method: System.Console.WriteLine("Hello World");
. In this example, we are saying ‘Hello World’ by printing it in the Console.
You can click on the "Start" button inside Visual Studio, to build and run this sample console application.
Output:
Note: I am using Console.Readkey() to show you line also, to keep console app runnning and show you output, which is not required, but you can use it if you are using Visual Studio.
As you can see in the above image we are reading User Key value using Console.ReadKey(), so basically using Console Class we can read values also.
using System;
namespace ReadLine
{
class Program
{
static void Main(string[] args)
{
Console.Write("What is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello {0}", name);
}
}
}
When exeucting above code, in the above code Console.ReadLine()
reads a value from a console and prints it.
We read a line from the terminal. When we hit the Enter key, the input is assigned to the name variable. The input is stored into the name variable, which is declared to be of type string.
Console.WriteLine("Hello {0}", name);
Output:
What is your Name? John //press "Enter" key after entering name
Hello John