Installation · Data Types · OOP · Collections · Exception Handling · Debugging
A comprehensive beginner-to-advanced guide to C# covering Visual Studio 2022 installation, variables, data types, strings, numbers, arrays, lists, dictionaries, functions, classes, structs, properties, inheritance, exception handling, and debugging techniques.
Table of Contents
- What is C#?
- Advantages and Disadvantages
- Installing Visual Studio 2022
- Creating Your First Project
- Hello World and Program Structure
- Variables and Data Types
- Type Conversion
- Booleans and Operators
- Working with Strings
- Working with Numbers and Formatting
- Getting User Input
- If Statements and Comparisons
- Switch Statements
- For Loops
- While Loops and Do-While
- Arrays
- Lists and Dictionaries
- Functions and Methods
- Parameters and Return Types
- Exception Handling (Try/Catch)
- Debugging in Visual Studio
- Structs and Classes
- Constructors, Fields, and Properties
- OOP: Getters, Setters, and ToString
- OOP: Inheritance and Overrides
1. What is C#?
C# (pronounced “C sharp”) is a modern, object-oriented programming language developed by Microsoft as part of its .NET platform. Released in 2000, it was designed by Anders Hejlsberg with the goal of combining the power of C++ with the simplicity of Visual Basic.
C# runs on the Common Language Runtime (CLR), which handles memory management and garbage collection. It is used for enterprise desktop apps, web backends (ASP.NET), mobile apps, game development (Unity), cloud services, and IoT systems.
Key Characteristics
- Strongly Typed: Every variable must have a declared type, catching errors at compile time.
- Object-Oriented: Built around classes, objects, inheritance, and polymorphism.
- Garbage Collected: The CLR automatically manages memory.
- Cross-Platform: With .NET 6+, C# runs on Windows, macOS, and Linux.
- Unity Integration: The default scripting language for the Unity game engine.
- Rich Ecosystem: NuGet hosts over 300,000 libraries.
2. Advantages and Disadvantages of C#
Advantages
| Advantage | Details |
|---|---|
| Type Safety | Strong typing catches errors before runtime. |
| Unity Integration | Default scripting language for the Unity game engine. |
| Modern Features | LINQ, async/await, pattern matching, records. |
| Cross-Platform | Runs on Windows, macOS, Linux, Android, iOS. |
| Excellent Tooling | Visual Studio provides world-class IntelliSense and debugging. |
| Performance | JIT compilation makes C# competitive in performance-sensitive tasks. |
| Enterprise Adoption | Widely used in banking, healthcare, and large-scale enterprise software. |
Disadvantages
| Disadvantage | Details |
|---|---|
| Windows Heritage | True cross-platform came late with .NET Core (2016). |
| Verbosity | More boilerplate than Python or JavaScript for simple tasks. |
| Learning Curve | OOP concepts and the .NET ecosystem take time to master. |
| Memory Footprint | The .NET runtime adds overhead vs native languages like Rust. |
3. Installing Visual Studio 2022
The Community edition is completely free for students and individual developers.
- Download: Go to visualstudio.microsoft.com and download the Community installer.
- Run the Installer: Double-click and accept the admin prompt.
- Select Workloads: Check .NET desktop development (approx. 6-7 GB).
- Install: Choose “Install while downloading” for fast connections.
- Sign In and Theme: Optionally sign in; choose Dark or Light theme.
- Reboot: Restart your computer after installation.
4. Creating Your First C# Project
Click Create a new project. Filter by Language: C#, Platform: Windows, Project type: Console. Select Console App (.NET Framework) and click Create.
using System;
namespace MyFirstProject
{
class Program
{
static void Main(string[] args)
{
// Your code goes here
}
}
}
The static void Main method is the entry point. It must be capitalized exactly as “Main”. C# is case-sensitive.
5. Hello World and Program Structure
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.ReadLine(); // keeps console window open
}
Press F5 to run. Without Console.ReadLine() the console window closes instantly.
WriteLine vs Write
Console.WriteLine("Hello"); // prints Hello, moves to next line
Console.Write("Hello"); // prints Hello, stays on same line
Console.Write(" World"); // continues: Hello World
6. Variables and Data Types
| Type | Description | Example | Notes |
|---|---|---|---|
int | 32-bit whole number | int age = 23; | -2.1B to +2.1B |
long | 64-bit whole number | long big = 90000L; | Add L suffix |
double | 64-bit decimal | double d = -55.2D; | Default decimal type |
float | 32-bit decimal | float f = 5.1F; | Add F suffix |
decimal | 128-bit precise decimal | decimal m = 14.99M; | Best for money |
string | Text | string name = "Aba"; | Double quotes |
char | Single character | char c = 'A'; | Single quotes |
bool | True or false | bool b = true; | Two values only |
Type Suffixes
long bigNum = 90000L; // L = 64-bit long
double d = -55.2D; // D = double
float f = 5.1F; // F = float
decimal money = 14.99M; // M = decimal (money)
var Keyword
var age = 23; // inferred: int
var name = "Aba"; // inferred: string
Constants
const int Vat = 20; // cannot be changed
// Vat = 25; // ERROR
7. Type Conversion
int age = Convert.ToInt32("23");
long bigNum = Convert.ToInt64("9000000000");
double negative = Convert.ToDouble("-55.2");
float prec = Convert.ToSingle("5.1");
decimal money = Convert.ToDecimal("14.99");
string ageStr = (23).ToString(); // "23"
Integer Division Gotcha
int r1 = 10 / 3; // 3 (decimal truncated!)
double r2 = 10.0 / 3; // 3.333...
double r3 = (double)10 / 3; // 3.333...
8. Booleans and Arithmetic Operators
bool isMale = true;
bool isTall = false;
int age = 23;
age++; // 24
age--; // 23
age += 10; // 33
age -= 5; // 28
age *= 2; // 56
age /= 4; // 14
int rem = 17 % 5; // 2 (remainder)
Odd or Even with Modulus
Console.WriteLine(10 % 2); // 0 = even
Console.WriteLine(11 % 2); // 1 = odd
9. Working with Strings
Escape Characters
| Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab |
\" | Double quote |
\\ | Literal backslash |
@"..." | Verbatim string (no escapes) |
String Concatenation
string name = "Aba";
int age = 23;
Console.WriteLine("Hello " + name + ", age " + age); // plus operator
Console.WriteLine($"Hello {name}, age {age}"); // interpolation (best)
Console.WriteLine("Hello {0}, age {1}", name, age); // composite
Common String Methods
string phrase = "C# Is Awesome";
phrase.ToUpper() // "C# IS AWESOME"
phrase.ToLower() // "c# is awesome"
phrase.Length // 13
phrase.Contains("Awesome") // true
phrase.Replace("Awesome","Great") // "C# Is Great"
phrase.Substring(0, 2) // "C#"
phrase.IndexOf("Is") // 3
phrase.Trim() // removes whitespace
phrase[0] // 'C'
Null Safety
if (string.IsNullOrEmpty(name))
Console.WriteLine("Name is empty or null");
string empty = string.Empty; // preferred over ""
10. Working with Numbers and Formatting
double value = 81.3456;
Console.WriteLine(string.Format("{0:0.00}", value)); // "81.35"
Console.WriteLine(string.Format("{0:0.0}", value)); // "81.3"
Console.WriteLine(string.Format("{0:0}", value)); // "81"
Currency Formatting
using System.Globalization;
double money = -3.33;
Console.WriteLine(money.ToString("C")); // local
Console.WriteLine(money.ToString("C", new CultureInfo("en-GB"))); // -£3.33
Console.WriteLine(money.ToString("C", new CultureInfo("en-US"))); // ($3.33)
Console.WriteLine(money.ToString("C", new CultureInfo("en-AU"))); // -$3.33
11. Getting User Input
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());
Safe Input with TryParse
if (int.TryParse(Console.ReadLine(), out int result))
Console.WriteLine($"You entered: {result}");
else
Console.WriteLine("Invalid number.");
Validation Loop
bool looping = true;
while (looping)
{
Console.Write("Enter a number: ");
if (int.TryParse(Console.ReadLine(), out int num))
{
Console.WriteLine($"Got: {num}");
looping = false;
}
else
Console.WriteLine("Invalid. Try again.");
}
12. If Statements and Comparisons
bool isMale = true;
bool isTall = false;
if (isMale && isTall)
Console.WriteLine("Tall male");
else if (isMale && !isTall)
Console.WriteLine("Short male");
else if (!isMale && isTall)
Console.WriteLine("Tall but not male");
else
Console.WriteLine("Not male and not tall");
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | age == 18 |
!= | Not equal to | age != 0 |
> | Greater than | age > 18 |
>= | Greater than or equal | age >= 18 |
< | Less than | age < 65 |
&& | AND | isMale && isTall |
|| | OR | isMale || isTall |
! | NOT | !isTall |
Ternary Operator
string result = age >= 0 ? "Valid age" : "Invalid age";
Console.WriteLine(age >= 18 ? "Adult" : "Minor");
13. Switch Statements
int day = Convert.ToInt32(Console.ReadLine());
switch (day)
{
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;
case 5: Console.WriteLine("Friday"); break;
case 6: Console.WriteLine("Saturday"); break;
case 7: Console.WriteLine("Sunday"); break;
default: Console.WriteLine("Invalid — enter 1 to 7"); break;
}
14. For Loops
for (int i = 0; i < 5; i++)
Console.WriteLine(i);
// Even numbers 0 to 10
for (int i = 0; i <= 10; i += 2)
Console.Write(i + " ");
// Times table
int num = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= 10; i++)
Console.WriteLine($"{i} x {num} = {i * num}");
FizzBuzz
for (int i = 1; i <= 100; i++)
{
bool div3 = (i % 3 == 0);
bool div5 = (i % 5 == 0);
if (div3 && div5) Console.WriteLine("FizzBuzz");
else if (div3) Console.WriteLine("Fizz");
else if (div5) Console.WriteLine("Buzz");
else Console.WriteLine(i);
}
15. While Loops and Do-While
int i = 0;
while (i < 5) { Console.WriteLine(i); i++; }
Guessing Game
string secretWord = "csharp";
string guess = "";
int guessCount = 0, guessLimit = 3;
bool outOfGuesses = false;
while (guess != secretWord && !outOfGuesses)
{
if (guessCount < guessLimit)
{
Console.Write("Guess: ");
guess = Console.ReadLine();
guessCount++;
}
else outOfGuesses = true;
}
Console.WriteLine(outOfGuesses ? $"You lose! Word was: {secretWord}" : "You won!");
Do-While
do
{
Console.Write("Enter positive number: ");
int n = Convert.ToInt32(Console.ReadLine());
if (n > 0) { Console.WriteLine($"Got: {n}"); break; }
Console.WriteLine("Must be positive.");
} while (true);
16. Arrays
int[] numbers = new int[] { 9, 4, 7, 2, 1, 8, 3 };
// Access
Console.WriteLine(numbers[0]); // 9
// For loop
for (int i = 0; i < numbers.Length; i++)
Console.Write(numbers[i] + " ");
// Foreach
foreach (int num in numbers)
Console.Write(num + " ");
Built-in Methods
Array.Sort(numbers);
Array.Reverse(numbers);
Array.Clear(numbers, 0, numbers.Length); // reset to 0
int idx = Array.IndexOf(numbers, 7);
Console.WriteLine(idx > -1 ? $"Found at {idx}" : "Not found");
17. Lists and Dictionaries
List
List<string> shopping = new List<string> { "Coffee", "Milk" };
shopping.Add("Bread");
shopping.Insert(0, "Tea");
shopping.Remove("Milk");
shopping.RemoveAt(1);
Console.WriteLine(shopping.Count);
Console.WriteLine(shopping.Contains("Tea")); // true
shopping.Sort();
shopping.Reverse();
foreach (string item in shopping)
Console.WriteLine(item);
Dictionary
Dictionary<string, string> states = new Dictionary<string, string>
{
{ "PA", "Pennsylvania" },
{ "NY", "New York" }
};
Console.WriteLine(states["NY"]);
if (states.TryGetValue("TX", out string name))
Console.WriteLine(name);
else
Console.WriteLine("TX not found");
states["NY"] = "New York (Updated)";
states.Remove("PA");
foreach (var pair in states)
Console.WriteLine($"{pair.Key} => {pair.Value}");
18. Functions and Methods
static void WelcomeMessage()
=> Console.WriteLine("Welcome!");
static string GetGreeting(string name) => $"Hello, {name}!";
static int Add(int a, int b) => a + b;
WelcomeMessage();
Console.WriteLine(GetGreeting("Aba")); // Hello, Aba!
Console.WriteLine(Add(5, 10)); // 15
Optional Parameters
static void Greet(string name = "stranger", int age = 0)
=> Console.WriteLine($"Hello {name}, you are {age}");
Greet(); // Hello stranger, you are 0
Greet("Aba", 23); // Hello Aba, you are 23
Named Parameters
static void PrintDetails(string name, int age, string address)
=> Console.WriteLine($"{name}, {age}, {address}");
PrintDetails(age: 23, address: "123 Main St", name: "Aba");
19. Parameters: out and ref
// By value — original unchanged
static void TestValue(int n) { n = 20; }
int num = 10;
TestValue(num);
Console.WriteLine(num); // still 10
// By reference — original IS changed
static void TestRef(ref int n) { n = 20; }
int num2 = 10;
TestRef(ref num2);
Console.WriteLine(num2); // now 20
// Out parameter
static bool TrySomething(string input, out int result)
{
result = 0;
return int.TryParse(input, out result);
}
if (TrySomething("42", out int parsed))
Console.WriteLine($"Parsed: {parsed}");
20. Exception Handling (Try/Catch)
try
{
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num);
}
catch (FormatException)
{
Console.WriteLine("Please enter a valid number.");
}
catch (OverflowException)
{
Console.WriteLine("Number too large. Max int: 2,147,483,647");
}
catch (Exception e)
{
Console.WriteLine($"Unexpected error: {e.Message}");
}
finally
{
Console.WriteLine("This always runs.");
}
Loop That Never Crashes
bool looping = true;
while (looping)
{
try
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"You entered: {num}");
looping = false;
}
catch (FormatException) { Console.WriteLine("Not a number."); }
catch (OverflowException) { Console.WriteLine("Too large."); }
}
21. Debugging in Visual Studio
Click in the left margin next to a line number to place a breakpoint (red dot). Press F5 to run — execution pauses at the breakpoint.
| Key | Action |
|---|---|
F10 | Step Over — execute current line |
F11 | Step Into — enter the called function |
Shift+F11 | Step Out — exit current function |
F5 | Continue to next breakpoint |
F9 | Toggle breakpoint on current line |
- Hover over any variable to see its value in a tooltip.
- The Locals window shows all in-scope variables.
- The Watch window lets you pin variables or expressions like
age > 18. - Values shown in red in Watch just changed on the last step.
- You can edit variable values during debugging by double-clicking in the Watch window.
22. Structs and Classes
Struct
struct Person
{
public string Name;
public int Age;
public Person(string name, int age) { Name = name; Age = age; }
}
Person p = new Person("Aba", 23);
Console.WriteLine($"{p.Name} is {p.Age} years old.");
Class
class Person
{
public string Name;
public int Age;
public Person() { }
public Person(string name, int age) { Name = name; Age = age; }
public string ReturnDetails() => $"Name: {Name}, Age: {Age}";
public override string ToString() => ReturnDetails();
}
Person person = new Person("Aba", 23);
Console.WriteLine(person); // calls ToString()
Struct vs Class
| Feature | Struct | Class |
|---|---|---|
| Type | Value type | Reference type |
| Inheritance | Not supported | Full inheritance |
| Best for | Small simple data | Complex objects with behavior |
23. Constructors, Fields, and Properties
Constructor Overloading
class Person
{
public string Name;
public int Age;
public Person() { Name = "Unknown"; Age = -1; }
public Person(string name) { Name = name; Age = -1; }
public Person(string name, int age) { Name = name; Age = age; }
}
Person p1 = new Person(); // Unknown, -1
Person p2 = new Person("Aba"); // Aba, -1
Person p3 = new Person("Aba", 23); // Aba, 23
Properties with Validation
class Person
{
private string name;
private int age;
public string Name
{
get { return name; }
set { name = string.IsNullOrEmpty(value) ? "Invalid" : value; }
}
public int Age
{
get { return age; }
set { age = (value >= 0 && value <= 150) ? value : -1; }
}
}
Auto-Implemented Properties
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age) { Name = name; Age = age; }
}
24. OOP: Getters, Setters, and ToString
class BankAccount
{
private decimal balance;
public decimal Balance
{
get => balance;
set => balance = value >= 0 ? value : 0;
}
public void Deposit(decimal amount)
{ if (amount > 0) balance += amount; }
public bool Withdraw(decimal amount)
{
if (amount <= balance) { balance -= amount; return true; }
return false;
}
}
Overriding ToString and Equals
public override string ToString()
=> $"Name: {Name}, Age: {Age}";
public override bool Equals(object obj)
{
if (obj is Person other)
return Name == other.Name && Age == other.Age;
return false;
}
Person a = new Person("Aba", 23);
Person b = new Person("Aba", 23);
Console.WriteLine(a.Equals(b)); // true
Console.WriteLine(a); // Name: Aba, Age: 23
25. OOP: Inheritance and Overrides
class Chef
{
public void MakeChicken() => Console.WriteLine("Chef makes chicken");
public void MakeSalad() => Console.WriteLine("Chef makes salad");
public virtual void MakeSpecialDish() => Console.WriteLine("Chef makes BBQ ribs");
}
class ItalianChef : Chef
{
public override void MakeSpecialDish()
=> Console.WriteLine("Italian chef makes eggplant parmigiana");
public void MakePasta()
=> Console.WriteLine("Italian chef makes fresh pasta");
}
Chef chef = new Chef();
ItalianChef ital = new ItalianChef();
chef.MakeSpecialDish(); // Chef makes BBQ ribs
ital.MakeSpecialDish(); // Italian chef makes eggplant parmigiana
ital.MakeChicken(); // Chef makes chicken (inherited)
ital.MakePasta(); // Italian chef makes fresh pasta
Key Inheritance Keywords
| Keyword | Purpose |
|---|---|
: | Denotes inheritance: class ItalianChef : Chef |
virtual | Marks a method in parent as overridable |
override | Overrides a virtual method in child class |
base | Calls the parent class method or constructor |
abstract | Forces child classes to provide an implementation |
sealed | Prevents further inheritance |
Calling Base Constructor
class Animal
{
public string Name;
public Animal(string name) { Name = name; }
}
class Dog : Animal
{
public string Breed;
public Dog(string name, string breed) : base(name)
{
Breed = breed;
}
public override string ToString() => $"{Name} ({Breed})";
}
Dog d = new Dog("Rex", "German Shepherd");
Console.WriteLine(d); // Rex (German Shepherd)
Congratulations! You have completed The Complete C# Programming Guide. You now have a solid foundation covering installation, syntax, collections, OOP, exception handling, and debugging. Next step: build real projects — a console game, a file manager, or a REST API with ASP.NET Core. Now just try to Keep building things it will get easier and best for you you need help just contact me on instagram or email me
0 Comments