Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write the first program in C#?
Writing your first program in C# is the foundation of learning this powerful programming language. A C# program consists of several key components that work together to produce output. Let's explore the structure and elements of a basic C# program.
Syntax
Following is the basic structure of a C# program −
using System;
namespace NamespaceName {
class ClassName {
static void Main(string[] args) {
// Program logic here
Console.WriteLine("Your message");
}
}
}
Example
using System;
namespace MyHelloWorldApplication {
class MyDemoClass {
static void Main(string[] args) {
// display text
Console.WriteLine("Hello World");
// display another text
Console.WriteLine("Welcome!");
}
}
}
The output of the above code is −
Hello World Welcome!
Understanding the Program Structure
Let us examine each component of the program −
-
using System; − The
usingkeyword imports theSystemnamespace, which contains fundamental classes likeConsole. -
namespace declaration − A
namespaceis a container that groups related classes. TheMyHelloWorldApplicationnamespace contains the classMyDemoClass. -
class declaration − The class
MyDemoClasscontains the data and method definitions. Classes are the building blocks of C# programs. -
Main method − The
Mainmethod is the entry point for all C# programs. When you run the program, execution begins here. -
Console.WriteLine() − This method from the
Consoleclass displays text on the screen. Each call prints the specified message followed by a new line.
Using Multiple Output Statements
Example
using System;
namespace MultipleOutputs {
class Program {
static void Main(string[] args) {
Console.WriteLine("Learning C# Programming");
Console.WriteLine("Program Output:");
Console.WriteLine("Line 1: Hello");
Console.WriteLine("Line 2: World");
Console.WriteLine("Line 3: Welcome to C#!");
}
}
}
The output of the above code is −
Learning C# Programming Program Output: Line 1: Hello Line 2: World Line 3: Welcome to C#!
Key Points
-
Every C# program must have a
Mainmethod as the entry point. -
C# is case-sensitive −
Mainis different frommain. -
Each statement ends with a semicolon (
;). -
Curly braces
{}define code blocks for namespaces, classes, and methods. -
Comments start with
//for single-line comments.
Conclusion
Your first C# program demonstrates the essential structure: namespace, class, and Main method. The Console.WriteLine() method provides a simple way to display output. Understanding these fundamental components prepares you for writing more complex C# applications.
