[go: up one dir, main page]

0% found this document useful (0 votes)
35 views41 pages

C#: From Darkness To Dawn

C#: From Darkness to Dawn A Beginner’s Journey Through Code, Logic, and Light C#: From Darkness to Dawn is your ultimate guide to transforming from a complete beginner into a confident C# programmer. Whether you're starting with zero knowledge or looking to strengthen your foundation, this book walks you step by step out of the confusion (“darkness”) and into clarity and skill (“dawn”). By Souhail Laghchim

Uploaded by

Souhail Laghchim
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views41 pages

C#: From Darkness To Dawn

C#: From Darkness to Dawn A Beginner’s Journey Through Code, Logic, and Light C#: From Darkness to Dawn is your ultimate guide to transforming from a complete beginner into a confident C# programmer. Whether you're starting with zero knowledge or looking to strengthen your foundation, this book walks you step by step out of the confusion (“darkness”) and into clarity and skill (“dawn”). By Souhail Laghchim

Uploaded by

Souhail Laghchim
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

introduction to C# (C-Sharp)

 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

Object-Oriented Supports classes, inheritance, polymorphism, encapsulation.

Type-Safe Prevents type errors (e.g., assigning a string to an int).

Access to .NET's Base Class Library (BCL) for file handling,


Rich Library
networking, etc.

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.

Modern Language Features LINQ, async/await, pattern matching, records, etc.

Popular for Game


Main language used in Unity game engine.
Development

 Setting Up C# Development Environment


You can write and run C# using:

 Visual Studio (Windows) – full-featured IDE.


 Visual Studio Code (cross-platform) – with C# extension.
 .NET SDK – download from https://dotnet.microsoft.com/.

Always download the latest, non-trial version.


 After Installing .NET SDK

Check Installation

Open Command Prompt or Terminal and type:

DMC:
 dotnet –version

You should see something like:

9.0.203

This confirms the .NET SDK is installed correctly.

Create Your First Project


In the terminal, create a console app:

DMC:
 dotnet new console -n MyFirstApp

 console = project type


 -n MyFirstApp = project name

Then navigate to your project folder:


DMC:
 cd MyFirstApp

Run Your App

To run the app, just type:

DMC:
 dotnet run

YAY !!—your first C# app is running!

Edit the Code


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:
DMC:
 dotnet run

Build the Project (Optional)

You can build the app manually with:

DMC:
 dotnet build

This compiles your app and creates an executable in the bin/ folder.

Optional: Use Visual Studio Code


If you're using VS Code:

 Install the C# extension from the Extensions tab.


 Open your project folder (MyFirstApp).
 You'll get IntelliSense, debugging, and more!

 Basic C# Program Structure


C#:
 using System;
 class Program

 {
 static void Main(string[] args)
 {
 Console.WriteLine("Hello, World!");
 }
 }

Explanation:

 using System; – imports the System namespace (includes Console).


 class Program – declares a class.
 static void Main(string[] args) – entry point of a C# program.
 Console.WriteLine() – prints output to the console.

 Data Types in C#
Value Types:

These store actual values directly in memory. Common examples include:

 Numbers (integers, floating points)


 Boolean (true/false)
 Char (single character)
 Structs and Enums also fall under value types.

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:

 Built-in types are provided by C# (like int, string, bool).


 User-defined types are created by developers (like custom classes or structs).

 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 Can You Build with C#?


 Desktop apps with Windows Forms or WPF
 Web apps using ASP.NET Core
 Mobile apps with Xamarin or MAUI
 Games with Unity
 APIs and microservices

Variables

 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;

 Common Data Types in C#

Type Example Description

int int x = 10; Integer number

float float y = 5.5f; Single precision float (use f at end)

double double d = 3.14; Double precision float

char char c = 'A'; Single character (single quotes)

string string name = "Alice"; Text (double quotes)

bool bool isOn = true; Boolean (true/false)

 Declaring and Initializing Variables


Declare and assign in one line:

C#:
 string city = "Oujda";
Declare first, assign later:

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:

 string city = "Oujda";


This creates a string variable named city and assigns it the value "Oujda" immediately.

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:

 Must start with a letter or _


 Can include letters, digits, and _
 Case-sensitive (Age and age are different!)

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
 }

If you try to use number outside MyMethod, you'll get an error.

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

⚠ var must be initialized immediately and can't change type later.

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:
 What are Data Types?
Data types define the type of data a variable can store. C# is strongly typed, so you must
specify a data type when declaring variables.

 Categories of Data Types in C#

Category Examples Description

int, float, double, char, bool, decimal,


Value Types struct
Hold actual data in memory

Reference
string, class, object, array, interface Hold reference to memory location
Types

Nullable Types int?, bool? Value types that can also be null

Used in unsafe code (rare in high-


Pointer Types int*, char* (unsafe context)
level C#)

 Value Types – Most Common Ones


Type Size Range / Example Use For

int 4 bytes -2,147,483,648 to 2.1B Whole numbers

long 8 bytes Bigger integers Large whole numbers

float 4 bytes ~6-9 digits of precision Small decimal numbers (add f)

double 8 bytes ~15-17 digits of precision General decimal numbers

decimal 16 bytes ~28-29 digits of precision Money, financial values

bool 1 byte true or false True/False logic

char 2 bytes A single character 'A' Single letters/symbols

 Reference Types

Type Example Description

string "Hello" Textual data

object object x = 10; Base type of all types

class public class Car {} User-defined objects

array int[] nums = {1,2,3} Collection of items of same type

 Nullable Types
You can make a value type nullable by using ?:

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}");
 }
 }

Useful for things like optional values, form inputs, etc.

 Type Conversion
Implicit (Safe):

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

 typeof & GetType()


You can check types at runtime:

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


Type Suffix Example

float f float f = 2.5f;

decimal m decimal d = 9.99m;

long L long l = 100000L;

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.

Type Suffix Purpose

Tells C# the number is a float (single-precision decimal). Without f, C# assumes it's


float f
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;

 if (age >= 18)

 {
 Console.WriteLine("You are an adult.");
 }

 if-else Statement
One block runs if true, another if false.

C#:
 int age = 16;

 if (age >= 18)

 {
 Console.WriteLine("Adult");
 }

 Else

 {
 Console.WriteLine("Minor");
 }

 if-else if-else Ladder


Used for multiple conditions.
C#:
 int score = 85;

 if (score >= 90)

 {
 Console.WriteLine("Grade: A");
 }

 else if (score >= 80)

 {
 Console.WriteLine("Grade: B");
 }

 else if (score >= 70)

 {
 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 (age >= 18)

 {
 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;

 }

Always use break to exit each case.

 Common Comparison Operators

Operator Meaning Example

== Equals x == 10
Operator Meaning Example

!= Not equal x != 5

> Greater than x > 20

< Less than x < 100

>= Greater than or equal x >= 5

<= Less than or equal x <= 10

 Logical Operators

Operator Meaning Example

&& AND x > 5 && x < 10

` `

! NOT !(x == 10)

Loops:
 What is a Loop?
A loop runs code repeatedly while a condition is true. It’s like saying:
"Do this again and again... until I say stop." 😎

 Types of Loops in C#

Loop Type Use Case

for loop When you know how many times to repeat

while loop When you repeat while a condition is true

do-while loop Like while, but runs at least once

foreach loop Used for iterating through collections

 for Loop
Use when the number of iterations is known.

C#:
 for (int i = 0; i < 5; i++)
 {
 Console.WriteLine("Count: " + i);
 }

Breakdown:

 int i = 0 → initialize counter


 i < 5 → condition
 i++ → increase counter each time
 while Loop
Repeats while the condition is true.

C#:
 int i = 0;
 while (i < 5)
 {
 Console.WriteLine("i is " + i);
 i++;
 }

If i < 5 is false, loop won’t run at all.

 do-while Loop
Runs code at least once, then checks the condition.

C#:
 int i = 0;
 do
 {
 Console.WriteLine("i is " + i);
 i++;
 }
 while (i < 5);

✅ Use this when you want to run first, check later.

 foreach Loop
Used to loop through arrays, lists, strings, etc.

C#:
 string[] fruits = { "Apple", "Banana", "Mango" };

 foreach (string fruit in fruits)


 {
 Console.WriteLine(fruit);
 }

foreach makes looping through collections super clean.

 Loop Control Statements

Statement What It Does

break Exit the loop immediately

continue Skip the current iteration and continue

Example with break and continue:

C#:
 for (int i = 1; i <= 5; i++)
 {
 if (i == 3)
 continue; // skip 3

 if (i == 5)

 break; // stop before printing 5


 Console.WriteLine(i);
 }

 Real-World Example: Sum of First 5 Numbers

C#:
int sum = 0;

for (int i = 1; i <= 5; i++)


{
sum += i;
}

Console.WriteLine("Sum = " + sum); // Output: 15

Function:
 What is a Function?
A function (or method) is a block of code that performs a specific task. Instead of repeating
code, you define it once and call it when needed.
 Basic Function Structure
C#:
returnType FunctionName(parameterList)
{
// code to execute
return value; // if not void
}

 Example: Basic Function


C#:
 void Greet()
 {
 Console.WriteLine("Hello, welcome!");
 }

To call this function:

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 With Return Value


C#:
 int Add(int a, int b)
 {
 return a + b;
 }

 int result = Add(5, 3);


 Console.WriteLine("Sum: " + result); // Output: Sum: 8

 Function Overloading
Same function name, different parameters.

C#:
 void Print(int num)
 {
 Console.WriteLine("Number: " + num);
 }

 void Print(string text)

 {
 Console.WriteLine("Text: " + text);
 }

C# figures out which version to call based on the argument type.

 Main() – The Starting Point


Every C# console app starts from Main():

C#:
 class Program
 {
 static void Main()
 {
 Greet();
 int sum = Add(2, 3);
 Console.WriteLine("Sum: " + sum);
 }

 static void Greet()

 {
 Console.WriteLine("Hi!");
 }
 static int Add(int a, int b)
 {
 return a + b;
 }
 }

 static vs non-static Functions


 static methods belong to the class.
 Non-static methods need an object of the class to be called.

Static Example:

C#:
 static void SayHi() { Console.WriteLine("Hi!"); }

Non-static Example:

C#:
 class MyClass
 {
 void SayHi() { Console.WriteLine("Hi!"); }
 }

 MyClass obj = new MyClass();


 obj.SayHi();

 Function With Multiple Parameters & Return


C#:
 double CalculateAverage(int a, int b, int c)
 {
 return (a + b + c) / 3.0;
 }

 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/

You might also like