C#: From Darkness To Dawn
C#: From Darkness To Dawn
What is C#?
C# (pronounced "C-Sharp") is a modern, object-oriented programming language developed by
Microsoft as part of its .NET platform. It is widely used for building Windows applications,
web services, games (using Unity), mobile apps (with Xamarin), and enterprise software.
C# is syntactically similar to Java and C++, but with simpler and more modern features.
Key Features of C#
Feature Description
Automatic Memory
Uses Garbage Collection to free up unused memory.
Management
With .NET Core / .NET 5+, C# apps can run on Windows, macOS,
Cross-Platform
and Linux.
Check Installation
CMD:
dotnet –version
9.0.302
CMD:
dotnet new console -n MyFirstApp
CMD:
cd MyFirstApp
CMD:
dotnet run
Open the Program.cs file (you can use any code editor like Visual Studio Code, Rider,
Notpad ++ or Visual Studio):
C#:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to C#!");
}
}
Change the message and save the file. Then run again:
CMD:
dotnet run
CMD:
dotnet build
This compiles your app and creates an executable in the bin/ folder.
Optional: Use Visual Studio Code
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
Explanation:
Reference Types:
These store references (or addresses) to the actual data in memory. Examples:
Strings
Arrays
Classes
Interfaces
Delegates
Nullable Types:
Allow value types to represent null, which normally only reference types can do.
Built-in vs User-defined:
Control Statements
If-Else
C#:
if (age >= 18)
Console.WriteLine("Adult");
Else
Console.WriteLine("Minor");
Loops
For Loop
C#:
for (int i = 0; i < 5; i++)
Console.WriteLine(i);
While Loop
C#:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
Object-Oriented Programming in C#
Class and Object
C#:
class Car
{
public string color;
public void Drive()
{
Console.WriteLine("Driving...");
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();
myCar.color = "Red";
myCar.Drive();
}
}
Advanced Concepts Overview
Inheritance: One class can inherit from another.
Interfaces: Define a contract that classes must implement.
Polymorphism: Methods behave differently based on context.
LINQ: Query data collections with SQL-like syntax.
Asynchronous Programming: async and await for concurrency.
What is a Variable?
A variable is like a labeled box in your computer’s memory that stores data. In C#, every
variable has a name, a type, and a value.
Syntax:
C#:
type variableName = value;
Example:
C#:
int age = 25;
C#:
string city = "Oujda";
C#:
int score;
score = 100;
In C#, you can declare and assign a variable in one line, or you can declare it first and assign
a value later.
For example, if you already know the value you want to store, you can do both at once:
But if you don't have the value right away, you can declare the variable first and assign it later:
int score;
score = 100;
Here, the variable score is declared first as an integer, and the value 100 is assigned to it
afterwards.
Both ways are valid—it just depends on when you have the value ready.
Variable Naming Rules
✅ Valid names:
C#:
using System;
class Program
{
int a = 5;
int A = 5;
string B = "Math";
string b = "Math";
static void Main(string[] args)
{
Program program = new Program();
Console.WriteLine(program.a);
Console.WriteLine(program.A);
Console.WriteLine(program.B);
Console.WriteLine(program.b);
}
}
🚫 Invalid:
C#:
int 2cool = 5; // ❌ starts with a number
string class = "Math"; // ❌ 'class' is a keyword
Variable Scope
Scope = where the variable "lives"
C#:
void MyMethod()
{
int number = 10; // only accessible inside MyMethod
}
The variable number is called a local variable. It only exists and is accessible within that
method (MyMethod in this case). This means if you try to use number outside of MyMethod, the
program will show an error saying the name doesn't exist in the current context.
Local variables are temporary and limited to the scope (or block) they are declared in.
In C#, when you create a variable inside a method, that variable is called a local variable. It only
lives and works inside that specific method. This means it can only be used while the method
is running, and only from within that method's block of instructions.
Once the method finishes, the variable disappears from memory, and you can’t use it anywhere
else in your program. If you try to access it outside the method, the program will show an error
because it doesn’t recognize it.
This is part of a concept called scope, which defines where a variable can be used. Local
variables have a limited scope, only inside the method or block where they were created.
C#:
using System;
class Program
{
static void Main()
{
// This variable only exists inside Main
int x = 10;
Console.WriteLine(x);
// This would fail - not in scope
// OtherMethod();
}
static void OtherMethod()
{
// Console.WriteLine(x); // Error - x not accessible here
}
}
Example: Using Different Variables
C#:
using System;
class Program
{
static void Main(string[] args)
{
int age = 19;
string name = "Shay";
bool isMarried = false;
float height = 5.9f;
char grade = 'A';
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
Console.WriteLine("Height: " + height);
Console.WriteLine("Married: " + isMarried);
Console.WriteLine("Grade: " + grade);
}
}
Bonus: var Keyword
C# allows you to use var to let the compiler figure out the type:
C#:
var language = "C#"; // automatically treated as string
var score = 90; // treated as int
C#:
using System;
class Program
{
static void Main()
{
var language = "C#"; // automatically treated as string
var score = 90; // treated as int
Console.WriteLine($"Language: {language}, Type: {language.GetType()}");
Console.WriteLine($"Score: {score}, Type: {score.GetType()}");
}
}
Data Types:
Nullable Types int?, bool? Value types that can also be null
Reference Types
C#:
using System;
class Program
{
static void Main()
{
int? nullableInt = null;
double? nullableDouble = 3.14;
Console.WriteLine(nullableInt.HasValue ? nullableInt.Value : "null");
Console.WriteLine(nullableDouble ?? 0);
// Null-coalescing operator provides default when null
int result = nullableInt ?? 0;
Console.WriteLine($"Result: {result}");
}
}
C#:
int x = 10;
double y = x; // int to double – safe
Explicit (Cast):
C#:
double a = 9.7;
int b = (int)a; // forcefully casting – decimal is dropped
C#:
int num = 5;
Console.WriteLine(num.GetType()); // System.Int32
Console.WriteLine(typeof(string)); // System.String
Code Example: All Main Types
C#:
using System;
class Program
{
static void Main()
{
int age = 19;
float pi = 3.14f;
double gravity = 9.81;
decimal price = 199.99m;
char grade = 'A';
string name = "Shay";
bool isPassed = true;
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Pi: {pi}");
Console.WriteLine($"Gravity: {gravity}");
Console.WriteLine($"Price: {price}");
Console.WriteLine($"Grade: {grade}");
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Passed: {isPassed}");
}
}
Tip: Suffixes to Remember
In C#, some numeric values need a suffix letter to clearly indicate their type. This is important
because, without the suffix, C# might assume a different type by default, which can lead to errors
or unwanted conversions.
f
Tells C# the number is a float (single-precision decimal). Without f, C# assumes
float
it's a double.
decimal m Tells C# the number is a decimal, often used for money or precise values.
long L Tells C# the number is a long integer, used for large whole numbers.
Each example in the table shows how to use the suffix when assigning a value to a variable of
that type.
Conditional Statements:
These are used to make decisions in your code — like, "If this happens, then do that."
if Statement
Executes code if a condition is true.
C#:
int age = 18;
{
Console.WriteLine("You are an adult.");
}
if-else Statement
One block runs if true, another if false.
C#:
int age = 16;
{
Console.WriteLine("Adult");
}
Else
{
Console.WriteLine("Minor");
}
if-else if-else Ladder
Used for multiple conditions.
C#:
int score = 85;
{
Console.WriteLine("Grade: A");
}
{
Console.WriteLine("Grade: B");
}
{
Console.WriteLine("Grade: C");
}
Else
{
Console.WriteLine("Fail");
}
Nested if Statements
You can place if statements inside others.
C#:
int age = 25;
bool hasID = true;
{
if (hasID)
{
Console.WriteLine("Access granted");
}
Else
{
Console.WriteLine("ID required");
}
}
Else
{
Console.WriteLine("Access denied");
}
Ternary Operator (? :)
Short version of if-else. One-liner!
C#:
int age = 20;
string result = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine(result);
switch Statement
Great for checking one variable against many possible values.
C#:
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;
}
== Equals x == 10
!= Not equal x != 5
Logical Operators
` `
Types of Loops in C#
for Loop
Use when the number of iterations is known.
C#:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Count: " + i);
}
Breakdown:
while Loop
Repeats while the condition is true.
C#:
int i = 0;
while (i < 5)
{
Console.WriteLine("i is " + i);
i++;
}
C#:
int i = 0;
do
{
Console.WriteLine("i is " + i);
i++;
}
while (i < 5);
foreach Loop
Used to loop through arrays, lists, strings, etc.
C#:
string[] fruits = { "Apple", "Banana", "Mango" };
C#:
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue; // skip 3
if (i == 5)
C#:
int sum = 0;
C#:
Greet();
Output:
CopyEdit
Hello, welcome!
Function With Parameters
C#:
void SayHello(string name)
{
Console.WriteLine("Hello, " + name + "!");
}
SayHello("Souhail");
Output:
CopyEdit
Hello, Alice!
Function Overloading
Same function name, different parameters.
C#:
void Print(int num)
{
Console.WriteLine("Number: " + num);
}
{
Console.WriteLine("Text: " + text);
}
C#:
class Program
{
static void Main()
{
Greet();
int sum = Add(2, 3);
Console.WriteLine("Sum: " + sum);
}
{
Console.WriteLine("Hi!");
}
static int Add(int a, int b)
{
return a + b;
}
}
C#:
static void SayHi() { Console.WriteLine("Hi!"); }
Non-static Example:
C#:
class MyClass
{
void SayHi() { Console.WriteLine("Hi!"); }
}
Best Practices
Give functions clear names (e.g., CalculateTax(), not DoStuff()).
Keep them small and focused on a single task.
Reuse them to avoid duplicating logic.
Email:
souhaillaghchim.dev@proton.me
Blogger:
https://souhaillaghchimdev.blogspot.com/