Mastering C#: A Journey Through Examples
Welcome to our comprehensive guide on C#, where we'll delve into the language through practical examples. C# is a powerful, modern, and expressive programming language developed by Microsoft. It's widely used for building a variety of applications, from web and mobile apps to games and enterprise software. Let's get started with some fundamental C# examples.
C# Basics: Hello World and Data Types
Every programming language journey begins with the classic "Hello, World!" example. In C#, it's as simple as:
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
C# is a statically-typed language, meaning you must declare the type of each variable. Here are some basic data types:

- Integer:
int x = 10; - Float:
float y = 3.14f; - Boolean:
bool z = true; - String:
string name = "John Doe";
Control Structures: If-Else and Loops
C# supports the usual control structures for decision-making and repetition. Here's an example of an if-else statement and a for loop:
int x = 10;
if (x > 5)
{
Console.WriteLine("x is greater than 5");
}
else
{
Console.WriteLine("x is not greater than 5");
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
Functions and Methods
In C#, you can define functions or methods to encapsulate reusable code. Here's a simple method that greets a person:
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
You can call this method like this:

Greet("Alice");
Classes and Objects
C# is an object-oriented language, meaning it supports the concepts of classes and objects. Here's a simple class definition:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Greet()
{
Console.WriteLine($"Hello, I'm {Name} and I'm {Age} years old.");
}
}
You can create an object from this class like this:
Person person = new Person { Name = "Bob", Age = 30 };
person.Greet();
Arrays and Lists
C# provides several collection types for storing multiple values. Here's an example of an array and a list:

- Array:
int[] numbers = new int[] { 1, 2, 3, 4, 5 }; - List:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Exception Handling
C# uses the try-catch-finally structure for exception handling. Here's an example:
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
}
finally
{
Console.WriteLine("This block always executes.");
}
LINQ (Language Integrated Query)
LINQ is a powerful feature in C# that enables you to query data using a syntax similar to SQL. Here's an example:
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 }
};
var adults = people.Where(p => p.Age >= 18).ToList();
This will create a new list containing only the adults.




















