C# Code Examples
Explore a variety of C# code examples demonstrating common programming tasks and advanced features. These examples are designed to help you understand and implement C# effectively.
1. Basic "Hello, World!" Program
A fundamental example to get started with C# console applications.
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
string message = "Hello, World!";
Console.WriteLine(message);
}
}
2. Simple Class and Object Creation
Demonstrates how to define a class, create an object, and access its members.
using System;
public class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public Dog(string name, int age)
{
Name = name;
Age = age;
}
public void Bark()
{
Console.WriteLine($"{Name} says Woof!");
}
}
public class Program
{
public static void Main(string[] args)
{
Dog myDog = new Dog("Buddy", 3);
myDog.Bark();
Console.WriteLine($"{myDog.Name} is {myDog.Age} years old.");
}
}
3. Looping and Conditional Statements
Illustrates the use of `for` loops and `if-else` statements.
using System;
public class LoopExample
{
public static void Main(string[] args)
{
int count = 0;
for (int i = 1; i <= 10; i++)
{
Console.WriteLine($"Iteration {i}");
if (i % 2 == 0)
{
Console.WriteLine(" This is an even number.");
count++;
}
else
{
Console.WriteLine(" This is an odd number.");
}
}
Console.WriteLine($"\nFound {count} even numbers.");
}
}
4. Working with Lists (Collections)
Demonstrates how to use the `List<T>` collection.
using System;
using System.Collections.Generic;
public class ListExample
{
public static void Main(string[] args)
{
List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");
Console.WriteLine("Fruits:");
foreach (string fruit in fruits)
{
Console.WriteLine($"- {fruit}");
}
fruits.Remove("Banana");
Console.WriteLine($"\nRemoved Banana. Count: {fruits.Count}");
}
}
5. Exception Handling (try-catch)
Shows how to gracefully handle potential errors.
using System;
public class ExceptionExample
{
public static void Main(string[] args)
{
try
{
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int number = int.Parse(input);
if (number == 0)
{
throw new DivideByZeroException("Cannot divide by zero!");
}
int result = 100 / number;
Console.WriteLine($"100 / {number} = {result}");
}
catch (FormatException ex)
{
Console.WriteLine("Error: Invalid input format. Please enter a valid integer.");
Console.WriteLine($"Details: {ex.Message}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred.");
Console.WriteLine($"Details: {ex.Message}");
}
finally
{
Console.WriteLine("\nOperation completed.");
}
}
}