// This is a single-line comment
/*
This is a
multi-line comment
*/
/// <summary>
/// This is an XML documentation comment
/// </summary>
Every C# program starts from the Main method:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
byte b = 255;
short s = 32000;
int i = 2147483647;
long l = 9223372036854775807L;
float f = 3.14f;
double d = 3.14159265359;
decimal m = 3.14m;
bool boolean = true;
char c = 'A';
string str = "Hello, World!";
object obj = new object();
dynamic dyn = 42;
// Variable declaration
int number;
// Variable initialization
number = 10;
// Declaration and initialization
string name = "John";
// Constants
const double PI = 3.14159;
// Implicitly typed local variables
var message = "Hello";
int a = 10, b = 3;
Console.WriteLine(a + b); // Addition: 13
Console.WriteLine(a - b); // Subtraction: 7
Console.WriteLine(a * b); // Multiplication: 30
Console.WriteLine(a / b); // Division: 3
Console.WriteLine(a % b); // Modulus: 1
int x = 5, y = 10;
Console.WriteLine(x == y); // Equal to: false
Console.WriteLine(x != y); // Not equal to: true
Console.WriteLine(x > y); // Greater than: false
Console.WriteLine(x < y); // Less than: true
Console.WriteLine(x >= y); // Greater than or equal to: false
Console.WriteLine(x <= y); // Less than or equal to: true
bool a = true, b = false;
Console.WriteLine(a && b); // Logical AND: false
Console.WriteLine(a || b); // Logical OR: true
Console.WriteLine(!a); // Logical NOT: false
int x = 10;
if (x > 0)
{
Console.WriteLine("Positive");
}
else if (x < 0)
{
Console.WriteLine("Negative");
}
else
{
Console.WriteLine("Zero");
}
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Other day");
break;
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// Foreach loop
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
int count = 0;
while (count < 5)
{
Console.WriteLine(count);
count++;
}
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < 5);
// Method definition
static int Add(int a, int b)
{
return a + b;
}
// Method overloading
static double Add(double a, double b)
{
return a + b;
}
// Method call
int sum = Add(5, 3);
double sumDouble = Add(5.5, 3.3);
// Optional parameters
static void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
// Named arguments
Greet(greeting: "Hi", name: "Alice");
// Array declaration and initialization
int[] numbers = { 1, 2, 3, 4, 5 };
// Accessing array elements
Console.WriteLine(numbers[0]); // Prints 1
// Multi-dimensional array
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// Jagged array
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
using System.Collections.Generic;
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
fruits.Add("Date");
fruits.Remove("Banana");
Console.WriteLine(fruits[0]); // Prints "Apple"
Console.WriteLine(fruits.Count); // Prints 3
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 },
{ "Charlie", 35 }
};
Console.WriteLine(ages["Bob"]); // Prints 25
ages["David"] = 40;
ages.Remove("Alice");
public class Car
{
// Fields
private string brand;
private string model;
// Properties
public int Year { get; set; }
// Constructor
public Car(string brand, string model)
{
this.brand = brand;
this.model = model;
}
// Methods
public void Start()
{
Console.WriteLine("The car is starting...");
}
// Getters and Setters
public string GetBrand()
{
return brand;
}
public void SetBrand(string brand)
{
this.brand = brand;
}
}
Car myCar = new Car("Toyota", "Corolla");
myCar.Year = 2022;
myCar.Start();
Console.WriteLine(myCar.GetBrand());
public class ElectricCar : Car
{
public int BatteryCapacity { get; set; }
public ElectricCar(string brand, string model, int batteryCapacity)
: base(brand, model)
{
BatteryCapacity = batteryCapacity;
}
public override void Start()
{
Console.WriteLine("The electric car is starting silently...");
}
}
public interface IDrivable
{
void Drive();
void Stop();
}
public class Car : IDrivable
{
public void Drive()
{
Console.WriteLine("The car is driving");
}
public void Stop()
{
Console.WriteLine("The car has stopped");
}
}
try
{
int result = 10 / 0;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Cannot divide by zero!");
}
finally
{
Console.WriteLine("This always executes");
}
// Throwing an exception
public void CheckAge(int age)
{
if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}
}
using System.Linq;
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Query syntax
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
// Method syntax
var oddNumbers = numbers.Where(x => x % 2 != 0);
var sum = numbers.Sum();
var average = numbers.Average();
var max = numbers.Max();
using System.Threading.Tasks;
public async Task<string> FetchDataAsync()
{
await Task.Delay(1000); // Simulating an async operation
return "Data fetched successfully";
}
// Usage
public async Task ProcessDataAsync()
{
string result = await FetchDataAsync();
Console.WriteLine(result);
}
using System.IO;
// Reading from a file
string content = File.ReadAllText("file.txt");
// Writing to a file
File.WriteAllText("output.txt", "Hello, World!");
// Reading lines from a file
string[] lines = File.ReadAllLines("file.txt");
// Appending to a file
File.AppendAllText("log.txt", "New log entry
");
public class Box<T>
{
private T item;
public void SetItem(T item)
{
this.item = item;
}
public T GetItem()
{
return item;
}
}
// Usage
Box<int> intBox = new Box<int>();
intBox.SetItem(10);
int value = intBox.GetItem();
// Delegate declaration
public delegate void MessageHandler(string message);
// Event declaration
public event MessageHandler MessageReceived;
// Method that matches the delegate signature
public void DisplayMessage(string message)
{
Console.WriteLine(message);
}
// Usage
MessageHandler handler = DisplayMessage;
handler("Hello, Delegate!");
// Event usage
MessageReceived += DisplayMessage;
MessageReceived?.Invoke("Hello, Event!");
2024 © All rights reserved - buraxta.com