What Is C#?
C# (pronounced "C sharp") is a modern, object-oriented programming language developed by Microsoft. It was first released in 2000 as part of the .NET framework and has grown into one of the most popular languages in the world — used for web backends, desktop apps, game development (Unity), and enterprise software.
If you've used Java before, C# will feel very familiar. If you're coming from JavaScript or Python, you'll need to get used to static typing, but the core logic concepts are the same.
Setting Up
Before writing code, you need:
Download .NET SDK from dotnet.microsoft.com
Install Visual Studio (Windows, full-featured) or VS Code with the C# extension (cross-platform)
To create your first console app:
bash
dotnet new console -n MyFirstApp
cd MyFirstApp
dotnet runYou'll see Hello, World! printed in the terminal. You're ready.
1. Variables and Data Types
C# is a statically typed language — you must declare the type of a variable when you create it.
csharp
int age = 25;
double price = 9.99;
bool isActive = true;
string name = "Soumar";
char initial = 'S';You can also use var and let the compiler infer the type:
csharp
var city = "Montreal"; // compiler knows this is a string
var count = 10; // compiler knows this is an intCommon types to know:
TypeDescriptionExampleintWhole number42doubleDecimal number3.14floatSmaller decimal3.14fdecimalHigh precision (money)9.99mboolTrue or falsetruestringText"hello"charSingle character'A'
Interview tip: Know the difference between double and decimal. Use decimal for financial calculations — it avoids floating-point precision errors.
2. Strings
Strings are one of the most used types. Here are the operations you need to know:
csharp
string first = "John";
string last = "Doe";
// Concatenation
string full = first + " " + last;
// String interpolation (preferred)
string greeting = $"Hello, {first} {last}!";
// String methods
string upper = name.ToUpper();
string lower = name.ToLower();
int length = name.Length;
bool contains = name.Contains("oh");
string trimmed = " hello ".Trim();
string replaced = "Hello World".Replace("World", "C#");
// Check if empty
bool isEmpty = string.IsNullOrEmpty(name);
bool isEmptyOrWhitespace = string.IsNullOrWhiteSpace(" ");3. Conditionals
csharp
int score = 75;
if (score >= 90)
{
Console.WriteLine("A");
}
else if (score >= 70)
{
Console.WriteLine("B");
}
else
{
Console.WriteLine("C or below");
}Ternary operator (shorthand if/else):
csharp
string result = score >= 60 ? "Pass" : "Fail";Switch statement:
csharp
string day = "Monday";
switch (day)
{
case "Monday":
Console.WriteLine("Start of the week");
break;
case "Friday":
Console.WriteLine("Almost weekend!");
break;
default:
Console.WriteLine("Just another day");
break;
}Switch expression (modern C# syntax):
csharp
string message = day switch
{
"Monday" => "Start of the week",
"Friday" => "Almost weekend!",
_ => "Just another day"
};4. Loops
csharp
// For loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// While loop
int x = 0;
while (x < 5)
{
Console.WriteLine(x);
x++;
}
// Do-while (runs at least once)
do
{
Console.WriteLine(x);
x++;
} while (x < 5);
// Foreach (iterating collections)
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}5. Arrays and Collections
Arrays — fixed size:
csharp
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
// Or shorthand
int[] scores = { 90, 85, 78 };List — dynamic size (use this more often):
csharp
using System.Collections.Generic;
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.Remove("Alice");
Console.WriteLine(names.Count); // 1Dictionary — key/value pairs:
csharp
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 25;
Console.WriteLine(ages["Alice"]); // 30
// Check if key exists
if (ages.ContainsKey("Bob"))
{
Console.WriteLine($"Bob is {ages["Bob"]}");
}Interview tip: Know the difference between Array, List, and Dictionary. Know when to use each one.
6. Methods (Functions)
csharp
// Basic method
static void SayHello()
{
Console.WriteLine("Hello!");
}
// Method with parameters and return value
static int Add(int a, int b)
{
return a + b;
}
// Method with optional parameters
static string Greet(string name, string greeting = "Hello")
{
return $"{greeting}, {name}!";
}
// Usage
SayHello();
int sum = Add(3, 4); // 7
string msg = Greet("Sou"); // Hello, Sou!
string msg2 = Greet("Sou", "Bonjour"); // Bonjour, Sou!7. Object-Oriented Programming (OOP)
This is the core of C#. You need to understand these four concepts: Encapsulation, Inheritance, Polymorphism, Abstraction.
Classes and Objects
A class is a blueprint. An object is an instance of that blueprint.
csharp
public class Person
{
// Properties
public string Name { get; set; }
public int Age { get; set; }
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Method
public void Introduce()
{
Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
}
}
// Creating an object
Person person = new Person("Soumar", 28);
person.Introduce();Inheritance
csharp
public class Animal
{
public string Name { get; set; }
public virtual void Speak()
{
Console.WriteLine("...");
}
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof!");
}
}
public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine("Meow!");
}
}
Animal dog = new Dog();
dog.Speak(); // Woof!Interfaces
An interface defines a contract — any class that implements it must provide the listed methods.
csharp
public interface IShape
{
double GetArea();
double GetPerimeter();
}
public class Circle : IShape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public double GetArea() => Math.PI * Radius * Radius;
public double GetPerimeter() => 2 * Math.PI * Radius;
}Interview tip: Interviewers love asking about the difference between an abstract class and an interface. Short answer: an abstract class can have implementation and state; an interface is purely a contract. In modern C# (8.0+), interfaces can have default implementations, but the principle still holds.
Access Modifiers
ModifierWho can accesspublicAnyoneprivateOnly within the same classprotectedSame class and subclassesinternalSame assembly/project
8. Exception Handling
csharp
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
Console.WriteLine("This always runs");
}Throw your own exceptions:
csharp
public void SetAge(int age)
{
if (age < 0)
throw new ArgumentException("Age cannot be negative.");
Age = age;
}9. LINQ (Language Integrated Query)
LINQ lets you query collections in a readable, SQL-like syntax. This comes up constantly in real projects.
csharp
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Filter
var evens = numbers.Where(n => n % 2 == 0);
// Transform
var doubled = numbers.Select(n => n * 2);
// Find first match
var firstBig = numbers.FirstOrDefault(n => n > 5); // 6
// Check if any match
bool hasNegative = numbers.Any(n => n < 0); // false
// Order
var sorted = numbers.OrderByDescending(n => n);
// Sum, Count, Average
int total = numbers.Sum();
int count = numbers.Count();
double avg = numbers.Average();
// With objects
List<Person> people = GetPeople();
var adults = people
.Where(p => p.Age >= 18)
.OrderBy(p => p.Name)
.Select(p => p.Name)
.ToList();Interview tip: Know the difference between First() and FirstOrDefault(). First() throws an exception if nothing is found; FirstOrDefault() returns null/default. Always prefer FirstOrDefault() unless you explicitly want the exception.
10. Async / Await
Modern C# applications are heavily asynchronous — especially web APIs. You must understand this.
csharp
using System.Threading.Tasks;
// Async method returns Task or Task<T>
public async Task<string> FetchDataAsync(string url)
{
using HttpClient client = new HttpClient();
string response = await client.GetStringAsync(url);
return response;
}
// Calling an async method
public async Task RunAsync()
{
string data = await FetchDataAsync("https://api.example.com/data");
Console.WriteLine(data);
}Key rules:
A method with
awaitmust be markedasyncasyncmethods returnTask(void) orTask<T>(with a return value)Never use
.Resultor.Wait()— it causes deadlocks. Alwaysawait
11. Nullable Types
csharp
// A regular int cannot be null
int age = null; // ERROR
// Nullable int can be null
int? age = null; // OK
// Null coalescing operator
int result = age ?? 0; // if age is null, use 0
// Null conditional operator
string? name = null;
int? len = name?.Length; // null if name is null, no crash12. Records (Modern C#)
Records are immutable data classes — great for DTOs and value objects:
csharp
public record Person(string Name, int Age);
var p1 = new Person("Alice", 30);
var p2 = new Person("Alice", 30);
Console.WriteLine(p1 == p2); // true — value equality, not referenceQuick Interview Cheat Sheet
TopicWhat to knowValue vs Reference typesint, bool, struct are value types; string, classes are reference types== vs .Equals()== compares references for objects; .Equals() compares valuesIEnumerable vs IListIEnumerable is read-only iteration; IList adds index access and modificationsealed classCannot be inheritedstaticBelongs to the class, not instancesGarbage collectorC# manages memory automatically — you don't free memory manually
What to Build to Practice
A console calculator — covers variables, methods, conditionals
A to-do list — covers Lists, loops, classes
A simple bank account — covers OOP, encapsulation, exceptions
A student grade calculator — covers LINQ, collections
A file reader/writer — covers async, exception handling
Final Thoughts
C# is a language that rewards learning its fundamentals properly. Most interview questions for junior and mid-level roles revolve around OOP concepts, LINQ, async/await, and basic data structures. Master those and you'll be able to walk into any C# interview with confidence.


