C# is a versatile programming language with a clear, structured syntax. This guide covers essential concepts including program structure, variables, control flow, and methods—the building blocks for creating functional C# applications.
Basic Program Structure
Every C# program requires:
- A class definition (the blueprint for your code)
- A Main method (the entry point where execution begins)
Example: “Hello, World!” Program
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
- Console.WriteLine() prints text to the console.
Variables and Data Types
Variables store data and must be declared with a type.
Common Data Types
Type | Example | Description |
---|---|---|
int | int age = 25; | Whole numbers |
string | string name = “John”; | Text |
double | double price = 9.99; | Decimal numbers |
bool | bool isActive = true; | True/False values |
Type Inference with var
The compiler can automatically detect the type:
var count = 10; // Compiler infers `int`
var message = "Hello"; // Infers `string`
Control Structures
Control structures dictate how code executes based on conditions or loops.
1. If-Else Statements
if (age >= 18)
{
Console.WriteLine("You're an adult.");
}
else
{
Console.WriteLine("You're a minor.");
}
2. Loops
For Loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i); // Prints 0 to 4
}
While Loop
int counter = 0;
while (counter < 3)
{
Console.WriteLine(counter);
counter++;
}
Methods (Functions)
Methods encapsulate reusable logic.
Defining a Method
public static int Add(int a, int b)
{
return a + b;
}
Calling a Method
int result = Add(5, 10);
Console.WriteLine(result); // Output: 15
Practical Example: Simple Calculator
class Calculator
{
static void Main(string[] args)
{
Console.WriteLine("Enter first number:");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter second number:");
int num2 = int.Parse(Console.ReadLine());
int sum = Add(num1, num2);
Console.WriteLine($"Sum: {sum}");
}
public static int Add(int a, int b)
{
return a + b;
}
}
Handling User Input
Use Console.ReadLine() to capture user input:
Console.WriteLine("What's your name?");
string userName = Console.ReadLine();
Console.WriteLine($"Hello, {userName}!");
Conclusion
Mastering these fundamentals—program structure, variables, control flow, and methods—enables you to build basic C# applications like calculators, interactive prompts, and more. These concepts serve as the foundation for advancing into more complex C# programming.
Next Steps:
- Explore arrays and collections
- Learn about object-oriented programming (OOP)
- Experiment with file I/O and error handling