a. Hello World Program
Let's begin by creating a simple "Hello World" program in C#. This classic example helps us understand the basic syntax and structure of a C# program.
1. Create a New Console Application:
If you haven't done so already, open Visual Studio and create a new console application following the steps mentioned in Tutorial 2.
2. Write the "Hello World" Code:
Open the Program.cs
file in the code editor and replace the existing code with the following:
3. Understand the Code:
using System;
: This line is an example of a using directive. It allows you to use types from theSystem
namespace without specifying the full namespace every time.class Program
: This declares a class namedProgram
. In C#, theMain
method, where the program starts executing, is typically located in a class namedProgram
.static void Main()
: This is the entry point of the program.Main
is a method (function) that serves as the starting point for program execution.Console.WriteLine("Hello, World!");
: This line uses theConsole
class to write the string "Hello, World!" to the console.WriteLine
adds a newline after the specified text.
4. Run the Program:
Press F5
or click the "Start Debugging" button to build and run your program. You should see the output in the console window: "Hello, World!"
5. Comments in C#:
Single-line comments: Created using
//
. Anything after//
on a line is a comment.Multi-line comments: Enclosed between
/*
and*/
. Everything between these markers is a comment.
6. Experiment:
- Try modifying the "Hello, World!" text.
- Add your comments to the code.
- Experiment with different
Console
class methods, likeConsole.Write
or formatting options.
Congratulations! You've successfully created and run a basic C# program. In the next tutorials, we'll explore variables, data types, and control flow statements.