C Sharp Complete Guide
C Sharp Complete Guide
C# Basics Fundamental
Get Started Composed Data
Preparing Work Array
Environment Arrays Definition
Install IDE (VS Code || Visual Arrays Method
Studio)
2 Dimensional Array
Creating your first project
Lists
Variables & Data Type Lists Definition
Types Of Data Type Declaring And Get List
Value Data Type Lists Methods
Reference Data Type
Dictionary
Type Casting Declaring Dictionary
Implicit Casting Get Dictionary Value
C# Programming Language 1
Explicit Casting Functions
Parse Method Functions Definitions And
Mathematic Operator Types
Addition Functions
Const keyword
Errors Handling
Control Flow Errors
Conditions Syntax Error
Exception Filter
String Syntax
Swallow & Duck Exception
Path Value Into String
String concatenation Debugging
String formatting ({0}) Debugging Mode
Numeric formatting
C# Programming Language 2
String interpolation ($) Set a breakpoint and start
debugging
Verbatim string literal (@)
String Methods Principles of defensive
programming
Empty string
Local/auto window
String Equals function
Watch window
String IsNullOrEmpty function
C# Intermediate
OOP (Object Oriented Advanced OOP Keywords
Programming) Principles Interfaces
Classes & Objects Interfaces
Class Member
Explicit interface implementation
Constructor
Classes Other Type
Extension Methods
Structures
Access Modifiers Enumeration
Public
Important Keywords
Private
Static Keyword
Internal
Namespaces Keyword
Protected
Project Structure
OOP Principles Concept
Files I / O Library
Inheritance
Stream (Reader & Writer) Class
Encapsulation
File Class
Polymorphism
Abstraction
Relationships Between
Classes
C# Programming Language 3
Association (Use a..)
Practice OOP
Tutorial Project (With Video) Exercise Project (No Video)
🏦 Design A Simple System Bank (Read 📒 Contact Manager
Only)
C# Programming Language 4
Tuples Covariance
Key Value Per Collections Contra-variance
Sorted List
IEnumerator
Indexers Others
Collections Exercise - Partial Class
Shopping System Project Partial Method
Nested Type
Basics Fundamental
Get Started
Preparing Work Environment
An integrated development environment (IDE) is software application that helps
programmers develop software code efficiently.
VS Code
chose console app (work for all platform, Mac, Windows, Linux) or console app (.NET
framework) (work for windows only).
C# Programming Language 5
check “Do not use top-level statements” if you want old format of C#. (Not a big deal)
click run button on top bar menu (CTRL + F5) to run your project.
C# Dev Kit
go to your project path in terminal then use this command to run project
dotnet run
Declaring Variables
to create variable, you have to specify the type and assign it a value.
C# Programming Language 6
string Name = "Medhat";
Type of Datatype
1. Value Datatype: directly store the variable value in memory and it will also accept both
signed and unsigned literals
2. Reference Datatype: contain a memory address of variable value because reference type
won’t store the value directly in memory
char Store character (16 byte) Example: ‘F’ Text based Datatype
Example:
Type Casting
when you assign a value of one datatype to another type.
there are tow types of casting
1. Implicit Casting
2. Explicit Casting
C# Programming Language 7
// char -> int -> long -> float -> double
int smallType = 20;
double largeType = smallType; // Automatic Casting
Console.WriteLine(largeType);
Mathematic Operator
Operation Symbol Example
Addition + x = x + y;
Subtraction - x = y - x;
Division / x = y / x;
Multiplication * x = y * x;
C# Programming Language 8
Operation Symbol Example
Reminder % x = y % x;
Example:
Keywords
are the words in a language that are used for some internal process or represent some
predefined actions.
Var Keyword
is a keyword, it’s used to declare and implicit type variable, that specifies the type of
variables based on initial value.
Const Keyword
if you don’t want others (or yourself) to overwrite value, you can add the const keyword
in front of the variable type.
C# Programming Language 9
//PI = 13.2; // Error Becuse you can't overwrite a constan
Control Flow
Conditional Statement
specify a block of C# code to be executed if a condition is true.
Conditions
Equal To == x == y
Not Equal To != x != y
Multiply Conditions
1. If Statement
C# Programming Language 10
int x = 10, y = 20;
if (x < y)
{
Console.WriteLine($"x:{x} is less than y:{y}");
}
else if (x == y)
{
Console.WriteLine($"x:{x} is equal y:{y}");
}
else
{
Console.WriteLine($"x:{x} is grater than y:{y}");
}
2. Switch Statement
int x = 2;
switch (x)
{
case 2:
Console.WriteLine("x = 2");
break;
case 5:
Console.WriteLine("x = 5");
break;
case 10:
Console.WriteLine("x = 10");
break;
default:
{
Console.WriteLine("No Conditon Role Success");
break;
}
C# Programming Language 11
Loop Statements
For Loop: When you know exactly how many times you want to loop through a block of
code.
While Loop: Loops can executed a block of code. as long as a specified condition is
true.
int j = 10;
while (j != 0)
{
Console.WriteLine(j);
j--;
}
Do While Loop: This loop will execute the code block once, before checking if
condition is true or not.
do
{
Console.WriteLine(2);
} while (3 > 4);
String Syntax
Path Value Into String
String Concatenation
String formatting
C# Programming Language 12
use to path a value into string without concatenation symbol
Numeric formatting
Currency Format
Console.WriteLine(money.ToString("C")); // equal to
Console.WriteLine(money.ToString("C1"));
Console.WriteLine(money.ToString("C2"));
CultureInfo.CurrentCulture()
C# Programming Language 13
deciaml money = 46.89M;
Console.WriteLine(money.ToString("C", CultureInfo.Cu
Console.WriteLine(money.ToString("C",
CultureInfo.CreateSpecificCulture("en-us")));
String Interpolation
String Methods
string.Empty
it used to represent Empty quotation mark “” , in clean code you should make your code
readable for any one work on project after you so let’s ask you which is better and
understandable easier:
C# Programming Language 14
} }
it used to represent == symbol like string.Empty for clean code and make your code
more readable for other programmer.
} }
Also up to you to chose but which is better for read do you think ?
string.IsNullOrEmpty
it is used to check whether the specified string is null or and empty string. A string will
be Null if it hasn’t been assigned value
if (string.IsNullOrEmpty(Name))
{
// Block of code
treat your string as array with characters type so you can loop on it write loop statement
and you can search on it for specify characters using .Contain() method that return bool
C# Programming Language 15
type and with .IndexOf() method that return address of your characters and now you can
get it easily.
Composed Data
Arrays
Array Definition
Array
its reference datatype, used to store multiple values in a single variables, instead of
declaring separate variables for each value.
To declare array
// First Way:
string[] arrOfName = { "Ahmed", "Medhat", "Samier" };
// Second Way:
string[] arr = new string[];
stringArr[0] = "Medhat";
stringArr[1] = "Samier";
C# Programming Language 16
stringArr[0] = "Medhat";
stringArr[1] = "Samier";
Console.WriteLine(stringArr[0]);
Console.WriteLine(stringArr[1]);
Array Methods
Array sorting
// Sort a string
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Array.Sort(cars);
foreach (string i in cars)
{
Console.WriteLine(i);
}
// Sort an int
C# Programming Language 17
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
foreach (int i in myNumbers)
{
Console.WriteLine(i);
}
Array reversal
Array.Reverse(spamLetters);
Array clearing
used to clear the contents of an array, returning each element to its default value.
Array.Clear(myArray, 0, myArray.Length);
Array IndexOf
searches for the specified object and returns the index of the first occurrence within
the entire one-dimensional Array.
int[] arr = { 100, 200, 300, 400, 500, 600, 700, 800, 90
2 Dimensional Array
if you want to store data as a tabular form, like a table with rows and columns, you need
to get familiar with multidimensional arrays.
Array can have any number of dimensions. the most common are
two-dimensional array (2D)
Create 2D Array
C# Programming Language 18
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Row 0 1 4 2
Row 1 3 6 8
Lists
Lists Definition
to create a collection of different types like integers, strings etc. List<T> class also
provides the methods to search, sort, and manipulate lists.
C# Programming Language 19
It is different from the arrays. A List<T> can be resized
dynamically, can accept null as valid value for reference type, also
allows duplicate element.
Declaring And Get List
firstlist.Add(5);
firstlist.Add(6);
firstlist.Add(7);
Lists Methods
C# Programming Language 20
Method Definition Example
collection to the end of the List<T>.
Returns a read-only
IList< int > readlist =
AsReadOnly ReadOnlyCollection<T> wrapper for firstlist.AsReadOnly();
the current collection.
Dictionary
used to store key/value pairs, the advantage of Dictionary is, it is generic type, it is dynamic
in nature means the size of the dictionary is growing according to the need.
its like lists but you have unique key to each element so you can’t
access element without this key
Declaring Dictionary
C# Programming Language 21
Get all data in dictionary
Functions (Methods)
Functions Definitions And Types
is a block of code which only runs when its called, can return any datatype you want, used to
perform certain actions and to reuse code (define the code once, use it many time).
Create Function
Types of return
C# Programming Language 22
Console.WriteLine(GetSum()); // 3
}
// Return string
public static string GetName()
{
return "My Name";
}
// Return Integer
public static int GetSum()
{
return 1 + 2;
}
Parameters (Arguments)
you can pass data, know as arguments, into method and used it in your code of function.
name, int age) , Arguments call to variables that passing to method like
this MyMethod(MyName,MyAge) , its not a big different and call it whatever
you want but just in case you need to know the different of naming.
C# Programming Language 23
static void Main(string[] args)
{
Equation(5 , 4 , 3 , 8, 9 , 10 , 2); //
}
// Dynamic Parameters
public static int Equation(int x, int y, params
{
int total = 0;
foreach (int i in arr)
{
total += i;
}
return x + y + total;
}
Named Parameters
You can path value to function using the name of variable not order in method.
Optional Parameters
C# Programming Language 24
you can use optional parameters by initialize variable while define it, and that make this
parameter is optional, if (developer / user) not (insert / initialize) it with any value, it will
use the default value of it.
Reference Parameters
ref is used to state that the parameter passed my be modified y the method.
Inner Parameters
in is used to state that the parameters passed can’t modified by the method.
C# Programming Language 25
//Inner Method
bool isEnrolled = false;
Enroll(isEnrolled);
}
Outer Parameters
out is used to state that the parameter passed must be modified by method, sam as
reference but can’t leave variable without modify it in method.
Error Handling
Error
Syntax Error
C# Programming Language 26
an error in the syntax of a sequence of characters that is intended to be written in a
particular programming language
Logic Error
ones where you don’t get the result were excepting, you wan’t see any red color wavy
line, and the Program generally won’t “but out” on you, in other words, you have made
an error in your programming logic (show at run time).
Exceptions
Handle Exception (Try / Catch)
the try statement allow you to define a block of code to be tested for errors while its
being executed.
the catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
cast = Convert.ToInt32(number);
C# Programming Language 27
try
{
cast = Convert.ToInt32(number);
}
catch
{
Console.WriteLine("Invaid Cast");
}
Exception Class
using exception class as base class for which exception inherit to represent an error.
try
{
cast = Convert.ToInt32(number);
}
catch (InvalidCastException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Built-in Exception
C# .Net includes built-in exception classes for every possible error, the exception class is
the base of all the exception classes.
C# Programming Language 28
Custom Exception
create a custom exception for user-defined exception.
using System;
Exception Filter
used it based on requirement you define for the exception, these handlers use the catch
statement with the when keyword.
C# Programming Language 29
try
{
//block of code
}
catch (Exception ex) when (ex.Message.Contains("404"))
{
//block of code
}
Debugging
Debugging Mode
Set a breakpoint and start debugging
2. Press F5, select the green arrow in the Visual Studio toolbar, or select Debug > Start
Debugging to start debugging. The debugger pauses on the breakpoint that you set.
Writing robust and reliable code is paramount for all software developers. However, no
matter how careful we are, bugs and unexpected situations can still occur. This is where
C# Programming Language 30
defensive programming comes into play. Defensive programming is a coding practice
aimed at ensuring that software functions correctly even when unexpected events or
invalid inputs occur.
1. Validate Input
Always validate input data to ensure that it meets the expected criteria before
processing it. This helps prevent runtime errors and ensures the stability of the
application.
2. Handle Exceptions
Anticipate potential failure points in your code and use exception handling
mechanisms such as try-catch blocks to gracefully handle errors and prevent crashes.
3. Fail Fast
Identify and report errors as soon as they occur rather than allowing them to
propagate through the system. This helps in pinpointing issues early in the
development process.
4. Use Assertions
Incorporate assertions into your code to enforce assumptions about the program’s
state. Assertions can help detect logical errors early during development and testing
phases.
Minimize the use of mutable state and prefer immutable data structures wherever
possible (see also “Understanding Mutable and Immutable Types in C#”). This
reduces the risk of unintended side effects and makes the code easier to reason
about.
6. Encapsulate Complexity
Encapsulate complex logic and dependencies within well-defined modules or
classes. This promotes modularity and reduces the likelihood of unintended
interactions between different parts of the codebase.
Local/auto window
The Autos window shows variables used The Locals window shows variables
around the current statement where the defined in the local scope, which is
debugger is paused. usually the current function or method.
C# Programming Language 31
Watch window
While you're debugging, you can use Watch windows and QuickWatch to watch
variables and expressions. The windows are only available during a debugging session.
Intermediate
Object Oriented Programming Principles (OOP)
Class Members
C# Programming Language 32
Variables inside a class called Fields, and that you can access them by create an object of
the class.
Class Constructors
is a special method that is used to initialize object.
The Advantage of a constructors:
C# Programming Language 33
class Car{ class Program{
public Car(string Mo }
{
model = Model;
}
Constructor Chaining
a technique in C# that allow one constructor to call another constructor of the same class
or a class base (parent)
// First Constructo
public Car() : this("Volvo")
{
model = "Nissan";
}
// Second Constructor
public Car(string Model)
{
model = Model;
}
Extension Method
allows you to add new methods in the existing class or in the structure without
modifying the source code of the original type.
The child class that have method you add have to be static.
C# Programming Language 34
public class ExtensionMethod static public class Extensio
{ {
public void SayHello() public static void SayWe
{ {
Console.WriteLine("He Console.WriteLine("H
} }
SayWelcomeAndHello
Function with
ExtensionMethodParent
instant object in your entry point
(Main).
Access Modifiers
Public → The Code is accessible for all classes
if you didn’t declare any access modifiers compiler will use Private
as default one.
Internal → The Code is only accessible within its own assembly (DLL Folder), but not
from another assembly(DLL Folder)
Protected → The Code is accessible within the same class, or in a class that inherited
from it
C# Programming Language 35
OOP Principles Concept
Inheritance
inherit fields and methods from one class to another,
inheritance concept into two category:
Virtual Keyword
The virtual keyword is used to modify a method, property, indexer, or event declaration
and allow for it to be overridden in a derived class.
Override Keyword
C# Programming Language 36
in Derived Class (Child) using override keyword to tell the compiler that this method
will be override from original one in parent class (Base Class).
// Parent (Sealed)
sealed class AnimalMoreInfo
C# Programming Language 37
{
public AnimalMoreInfo()
{
Console.WriteLine("This is Fantasi Animal");
}
}
}
}
Encapsulation (Properties)
is to make sure that “Sensitive” data is hidden from user to access them you have to:
provide (get & set) method. through properties to access and update the value of private
field.
class Person
{
private string? _name;
public string? Name
{
get
{
// Logic
if (_name != "No Name")
{
return _name;
}
else
{
return "No Name Entered Please ReEnter you
}
}
C# Programming Language 38
set
{
// Logic
_name = !string.IsNullOrEmpty(value) ? value :
}
}
// Smart Properties
public int Age { get; /* set; */} = 25;
}
Smart Properties: in C# you can create encapsulation properties in one line, if you
not need a logic code to set or get that variable, you can just control of read and
write of variable if you use smart properties to control it.
Polymorphism
means “Many Forms”, and it occurs when we have many classes that are related to each
other by inheritance.
it is useful for code reusability: reuse fields and methods of an existing class when you
create a new class.
C# Programming Language 39
// Dynamic Polymorphism (RunTime Polymorphism), Interface,
class Monster // Base Class
{
public virtual void MakeSound()
{
Console.WriteLine("Monster Make Sound");
}
}
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
C# Programming Language 40
{
total += item;
}
return total + a;
}
}
Abstraction
is the process of hiding certain details and showing only essential information to the user.
// Concrete
public void Close()
{
Console.WriteLine("Shop Closing");
}
}
C# Programming Language 41
public override void Open()
{
Console.WriteLine("Clothing Shop Open");
}
}
Hiding Method: it’s a concept of Polymorphism, but what if you want not to use
the override method and want your object yo use base method from parent class And
that what Hiding Method do.
C# Programming Language 42
public class Cat : Animal // Child Class
{
public new void MakeSound() // new keyword use to ac
{
Console.WriteLine("Cat makes a sound.");
}
}
// Method Hiding
Animal animal1 = new Animal();
Animal cat1 = new Cat();
// Cat animal2 = new Animal(); // Compilation error - ca
Cat cat2 = new Cat();
C# Programming Language 43
}
}
// Method Hiding
Animal animal1 = new Animal();
Animal cat1 = new Cat();
// Cat animal2 = new Animal(); // Compilation error - ca
Cat cat2 = new Cat();
its about lifetime of classes and how class work together in big projects.
Association (Use a)
Mean that class A use class B, but class A lifetime not depend on class B lifetime.
class Department
{
public string? Name { get; set; }
}
class Employee
{
public string? Name { get; set; }
C# Programming Language 44
Aggregation (Has a)
When class A has class B as fields, but not using it, if class A Deleted, it will not
effect class B, it will just belong to the new class A.
class Department
{
public string? Name { get; set; }
}
class Company
{
public string? Name { get; set; }
Composition (Owns a)
when class A has and use class B as fields, if class A Deleted, class B will get
deleted also, because class A own class B.
class Vicale
{
public string? Name { get; set; }
class Engine
{
public string? Model { get; set; }
C# Programming Language 45
public int CC { get; set; }
}
An interface is a completely "abstract class", which can only contain abstract methods and
properties (with empty bodies).
It is considered good practice to start with the letter "I" at the beginning
of an interface, as it makes it easier for yourself and others to remember
that it is an interface and not a class.
Interface Rules
you have to implement all method you create in interface in base class (Parent).
C# Programming Language 46
Interface can inherit from another interface (one or more).
when you have multi interface that have same properties with same name, how you
detected which interface you need to use it’s methods or fields and here come explicitly
implementation.
C# Programming Language 47
{ Console.WriteLine(shape.Calc
return "Blue"; IColor color = circle;
} Console.WriteLine(color.Calc
}
its value type whereas a class is reference type, more complex of simple type, and look
exactly like class.
Enumeration
C# Programming Language 48
An enum is a special "class" that represents a group of constants (unchangeable/read-
only variables).
enum DaysOfWeek
{
Monday = 2,
Tuesday = 3,
Wensday = 4,
Thrusday = 5,
Friday = 6,
Satrday = 0,
SunDay = 1
}
enum TraffecLight
{
Green = 1,
Yellow = 2,
Red = 3
}
switch (enumInput)
{
case TraffecLight.Red:
C# Programming Language 49
{
Console.WriteLine("Start");
break;
}
case TraffecLight.Yellow:
{
Console.WriteLine("Prepare");
break;
}
case TraffecLight.Green:
{
Console.WriteLine("Go");
break;
}
default:
{
Console.WriteLine("Chose number between 1 - 3 i
break;
}
}
Important Keywords
Static Keyword
Classes
Variables
Methods
Constructor
its Utility for use in code not to store data, and can’t make instant of static class.
C# Programming Language 50
public static string? MotherName;
}
}
C# Programming Language 51
Console.WriteLine(NumberOfCalls);
}
}
Family.FatherName = "Ziad";
Family.MotherName = "Ola";
Console.WriteLine(Family.HasFamily());
NameSpace
Used to organize the classes. it helps to control the scope of methods and classes in larger
projects.
namespace name_of_nameSpace
{
// Nested NameSpace
namespace name_of_nestedNameSpace
{
//Classes
class class_name
{
//Interfaces
interface interface_name
{
C# Programming Language 52
//Structures
struct struct_name
{
//Delegates
delegate void delegate_name(); // Talk Bout it later
Project Structure
Files I/O Library
we have two class we can use to deal with files and each include into Files I/O Library.
stream is a wrapper or an abstract class that provides the required methods to read, write,
and perform other relevant operations with bytes.
string? line;
while ((line = stream.ReadLine()) != null)
{
foreach (char c in line)
{
Console.Write(c);
Thread.Sleep(250);
C# Programming Language 53
}
Console.Write(" ");
File Class
provide some static method to perform most file operation, such as creating file, copying
and moving a files, deleting files, and work with “File Stream” to read and write stream.
string message =
@"Hello Every One
This text from C# program
this simulation of log file in any C# project using File s
C# Programming Language 54
if (File.Exists(FilePath))
{
Console.WriteLine("File Already Exist");
}
else
{
//Create New text
File.WriteAllText(FilePath, message);
Advanced
Collections
Generics
Generics Definition
Story: you have a client that want you display product (Name, Price) in application
with integer price and string name, you accept and make this code
class Product{
string Name? {get; set;}
int Price {get; set;}
C# Programming Language 55
Price = 20
}
product.ShowProduct();
That good but then the client came back and ask to show the price in decimal format
but keep the old formate as the same, you accept and do this
class Product{
string Name? {get; set;}
int Price {get; set;}
class ProductWithDecimal{
string Name? {get; set;}
decimal Price {get; set;}
C# Programming Language 56
Name = "P1",
Price = 20.50
}
decimalProduct.ShowProduct();
}
Thats perfect, then the client came back to make some change about name datatype
to be integer ID, you said to him that will be infinity of classes of possible changes
so the code will be non-readable and performance of app will be bad, and you lose
your client 🥲
Generic is declaring datatype of (class, method, fields, ..) at initialize it,
so you can use different datatype with the same (class, method, fields,
..).
Generics Class
product.ShowProduct();
C# Programming Language 57
Product<string, decimal> productTwo = new Product<string
{
Name = "P1",
Price = 20.50m
};
productTwo.ShowProduct();
productThree.ShowProduct();
now you make all client possible change with just one class, with readable code, and
better performance.
Generics Method
Generics interface
C# Programming Language 58
public class Box<T> : IContainer<T>
{
public void Add(T name)
{
// Block of Code
}
}
Generics Constrains
you can set some constrains to your generics type to make sure other developer not use
some type that make logic error on your code.
circle.Add("Medhat");
C# Programming Language 59
// circle.Add(10);
you can add more than one constraint in the same generics type.
Collections in C#
Generics Collection
Collection you can use when you want all collection value to be same datatype, and that
make some advantage in your code like:
High Performance.
Type-Safe coding.
Readability.
Non-Generics Collection
Collection you can use when you don’t care about datatype you just want to store data in
some collection, but this collection make some disadvantage to your code like:
Low Performance.
Bad Readability.
Example: ArrayLists
Array List
is non-generics collection type and its dynamic size so you not need to know size of your
list at initializing, but its has no datatype define.
Example:
C# Programming Language 60
arrayList.Add("String in Array List"); // Boxing
arrayList.Add(5);
arrayList.Add(10);
arrayList.Add(15);
Console.Write(arrayList[0]); // Unboxing
arrayList.Remove(10);
arrayList.RemoveAt(2);
arrayList.AddRange(arr);
But like we said before it has disadvantage to use because its Non-Generics Collection.
Stack is Generics & Non-Generics Collection you can use both of them but
Generics s better, and its Dynamic size
C# Programming Language 61
Mean last value add to stack it will be first one to get out from the stack using
Push() and Pop() Methods to make this action.
stack.Push(5);
stack.Push(3);
stack.Push(9);
// stack.Push("Text");
Console.WriteLine(stack.Pop()); // 9
Console.WriteLine(stack.Pop()); // 3
Queue is Generics & Non-Generics Collection you can use both of them but
Generics s better, and its Dynamic size
C# Programming Language 62
Mean First value add to queue it will be first one to get out from the queue using
Enqueue() and Dequeue() Methods to make this action.
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
queue.Enqueue(4);
Console.WriteLine(queue.Dequeue()); // 1
Console.WriteLine(queue.Dequeue()); // 2
Console.WriteLine(queue.Dequeue()); // 3
Tuple
C# Programming Language 63
its not collection but it more like build in class that you can stored data into it with
different data type and its Generics type, Reference value but it have some properties
you should follow it (Max data you can store in it is 8 fields.)
use tuple to return more than one value from function instead of (out
, ref) parameters.
Console.WriteLine(tuple.Item1); // 24
Console.WriteLine(tuple.Item2); // Medhat
Console.WriteLine(tuple.Item3); // false
Console.WriteLine(Employee1.Rest.Item1.Item2); // Ali
Console.WriteLine(GetNameAndAge().Item1);
Console.WriteLine(GetNameAndAge().Item2);
C# Programming Language 64
(string,string,int) car = ("Nissan" , "Hatshback" , 2009
Console.WriteLine(car.Item1); // Nissan
Console.WriteLine(car.Item2); // Hatshback
Console.WriteLine(car.Item3); // 2009
Console.WriteLine(CarModel);
Console.WriteLine(CarYear);
Using Example:
Setting.
Cashing.
Sorted List
Generics Collection Type, its like dictionary at everything but its Sorted.
C# Programming Language 65
SortedList<int, string> sortedList = new SortedList<int, s
{2,"Medhat"} ,
{1, "Ahmed"}
};
Hash Table
Collection Internal
IEnumerable
let’s create new collection called ShopList that implement IEnumerable interface
C# Programming Language 66
public class ShopingList : IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
now as you can see ShopingList class have GetEnumerator method from IEnumerable
interface and this method return an collection (List , Array , Stack ….).
IEnumerator
IEnumerator is a (Person) who deal with all data in our list, it get the
data from GetEnumerator method.
MoveNext: return true if the position move forward to next value successfully, and
return false when it can’t get the next value of our list.
C# Programming Language 67
Reset: reset the position to start point when foreach finished the process.
return true;
}
else
{
return false;
}
}
C# Programming Language 68
}
}
As we can see we create constructor to get our list from ShopingList class, create
position variable to control the position of list, and set condition in MoveNext method to
make sure our position will move correctly.
now we ready to test foreach method in our application with this new collection call
ShopingList.
And This how all collection work in C# with deferent Logic but same
way as they implement IEnumerable interface and using IEnumerator to
deal with value.
Indexer
C# Programming Language 69
in any collection you can get and set value in collection using index like this
list.Add(5); // Index 0
list.Add(3); // Index 1
list.Add(8); // Index 2
Console.WriteLine(list[1]); // 3
Now let’s go Under the hood to know how indexer work and create customs indexer
Main Goal is create object from BookCollection and use index to set
& get Book Class info to our array in BookCollection Class
Indexer is a normal properties with get and set but return the type of class you stored in
collection array.
Customs indexer useful when you need to add your logic to the collection because each
collection you use has its own logic.
C# Programming Language 70
{
return books[Index];
}
set
{
books[Index] = value;
}
}
Console.WriteLine(bookCollection[0].Title);
Console.WriteLine(bookCollection[0].Author);
In customs indexer you can make indexer overloading to make your collection able to get
or set with different datatype & value.
C# Programming Language 71
public Book this[string Title]
{
get
{
foreach (var book in books)
{
if (book.Title == Title)
{
return book;
}
}
return null;
}
set
{
for (int i = 0; i < books.Length; i++)
{
if (books[i].Title == Title)
{
books[i] = value;
return;
}
}
C# Programming Language 72
Console.WriteLine(bookCollection["GOT"].Title);
Console.WriteLine(bookCollection["Lord of the ring"].Autho
A delegate is an object which refers to a method or you can say it is a reference type
variable that can hold a reference to the methods.it provides a way which tells which
method is to be called when an event is triggered.
Example:
C# Programming Language 73
return result;
}
return result;
}
we can’t have two function doing the same operation try to Using (DRY) principle.
return result;
}
Ok that good. but what if we need to Get number Less than to grater than what can we do?
(Without Create another functions).
C# Programming Language 74
delegate bool CheckDelegates(int numOne, int numTwo); // Decla
return result;
}
At Main Method:
C# Programming Language 75
Console.WriteLine(item);
}
And now we have just one function with multi operation and without limit numbers of choice.
we will explain this chapter using delegates so make sure that you understand how
delegates work.
C# v.2 : Anonymous Methods Created and can be use to make delegates method be
inline (one line of code) Example:
Before Anonymous Methods
C# Programming Language 76
return x < y;
}; // Anonymous Method (instations)
Now as you see we create a call of method that need delegate as parameters , but
without take instance of delegate or create new one, with lamda expressions we can
create and initializing delegate in one line.
Delegate Chains
we have three methods with string return type and one string parameter, and one
delegate.
C# Programming Language 77
Console.WriteLine(delegateChain("My String"));// Me
}
GetInvocationList()
return Array of Delegate which inside of delegate object, and each method have two
properties (Method, Target)
Target: return the class which have the method inside it, and return null if
method was static because static can’t have instance object.
Generics Delegates
We have two method one of then int return type and other is string return type, create a
delegate for this 2 method.
before you go and create delegate for each method , let’s use generics delegate.
Console.WriteLine(sumIntOrString1(1, 2)); // 3
Console.WriteLine(sumIntOrString2("Medhat", " Assem"))
}
C# Programming Language 78
Func : its a delegate take up to 16 parameters and its build-in in .Net Framework,
and its generics type, it can’t return void type,
Console.WriteLine(func(5, 2)); // 7
Actions
its like a Func but its used to return void type only.
Action < Parameters ,..> ActionName = Method;
action("Medhat", "Assem");
Predicate
its like Func And Action but its Used to return boolean type, and it take only one
parameters.
Predicate < Parameters > PredicateName = Method;
Console.WriteLine(predicate(4));
C# Programming Language 79
Events
Events & Observer Pattern
We need to create application that user can upload new video to his youtube channel
and subscriber get notification that user upload new video and they can watch it.
}
}
}
public void WatchTheVideo(string videoName)
{
Console.WriteLine($"Watching {videoName}");
}
Now let’s create a delegate to point the UploadVideo method in subscriber class
C# Programming Language 80
public void UploadVideo(string videoName)
{
Console.WriteLine($"{videoName} Uploaded");
videoUpload(videoName);
}
}
subscriberOne.Subscrib(channel);
subscriberTwo.Subscrib(channel);
subscriberThree.Subscrib(channel);
channel.UploadVideo("Video One");
channel.UploadVideo("Video Two");
channel.UploadVideo("Video Three");
C# Programming Language 81
1. Direct Invoke : subscriber get notification without uploading any video
channel.videoUpload("x");
2. Set Delegate Object To Null : That will delete all your subscriber when
upload video
channel.videoUpload = null;
Event Keyword Solve This Problem by prevent the to line of code to work (Give
syntax Error)
its a build in Delegate that have 2 parameters, and its has 2 type to use:
}
}
C# Programming Language 82
public class Subscriber
{
public void Subscrib(YouTubeChannel channel)
{
channel.videoUpload += WatchTheVideo;
}
public void WatchTheVideo(object sender, EventArgs e
{
Console.WriteLine($"Watching Video");
}
With Delegates
C# Programming Language 83
public delegate Apple CreateAppleDelegate();
// First Way
CreateAppleDelegate createApple = apple1.CreateNewApple;
createApple();
// Second Way
CreateFruitDelegate createFruitDelegateApple = apple1.Crea
CreateFruitDelegate createFruitDelegateOrange = orange1.Cre
// Third Way
CreateFruitDelegate createFruitDelegate = apple1.CreateNewA
createFruitDelegate += orange1.CreateNewOrange;
createFruitDelegate();
Contra-Variance
Asynchronous Programming
Threading
Others
C# Programming Language 84
Partial Class
A partial class is a special feature of C#. It provides a special ability to implement the
functionality of a single class into multiple files and all these files are combined into a single
class file when the application is compiled.
class Program
{
static void Main(string[] args)
{
#region Partial Class
#endregion
}
}
Advantages :
C# Programming Language 85
With the help of partial classes, multiple developers can work simultaneously in the same
class in different files.
With the help of a partial class concept, you can split the UI of the design code and the
business logic code to read and understand the code.
When you were working with automatically generated code, the code can be added to the
class without having to recreate the source file like in Visual studio.
You can also maintain your application in an efficient manner by compressing large
classes into small ones.
Partial Method
C# contains a special method is known as a partial method, which contains declaration part in
one partial class and definition part in another partial class or may contain both declaration
and definition in the same partial class.
Finalizer (OOP)
its a method inside a class used to destroy instances of that class.
C# Programming Language 86
~Finalizer()
{
Console.WriteLine("This is Finalizer Destructor");
}
}
Nested Type
its define class inside another class.
}
}
C# Programming Language 87
NewClass.NestedClass nestedClass = new NewClass.NestedClass()
C# Programming Language 88