Running head: Awais Saleem1
Lecture No:2
Awais Saleem
C Sharp Notes:
Author Note
[Include any grant/funding information and a complete correspondence address.]
2
Lecture No .01
Keywords: Data Types in C sharp:
In C#, data types specify the type of data that a variable can hold. They are broadly divided
into value types and reference types
VALUE TYPES
Value types directly contain their data. Common examples are numbers, characters, and
structures.
1. PRIMITIVE TYPES
These are predefined by the language:
INTEGRAL TYPES
o byte (8 bits, 0 to 255)
o sbyte (8 bits, -128 to 127)
o short (16 bits, -32,768 to 32,767)
o ushort (16 bits, 0 to 65,535)
o int (32 bits, -2,147,483,648 to 2,147,483,647)
o uint (32 bits, 0 to 4,294,967,295)
o long (64 bits, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
o ulong (64 bits, 0 to 18,446,744,073,709,551,615)
FLOATING-POINT TYPES
o float (32 bits, 6-9 digits precision)
o double (64 bits, 15-17 digits precision)
o decimal (128 bits, 28-29 digits precision, primarily used in financial
calculations)
OTHER
o char (16 bits, a single Unicode character) // string a =’Awais’; always store
single commma:
o bool (1 bit, true or false)
2. STRUCTURES
Custom value types created using struct.
3
REFERENCE TYPES
Reference types store references to their data (the data is stored in the heap).
1. CLASS TYPES
Defined using class.
Example: string, Object. // string a =” Awais”; always store two commma:
2. ARRAY TYPES
Examples: int[], string[]
4
Lecture No:2
In C#, data type conversion refers to converting one type of data to another. C# provides several
mechanisms for type conversion, including implicit conversion, explicit conversion, and
helper methods
1. Implicit Conversion
Automatically performed by the compiler.
Happens when there is no risk of data loss.
int num = 123;
double d = num; // Implicit conversion from int to double
2. Explicit Conversion (Type Casting)
Must be explicitly specified by the programmer.
Required when there is a potential for data loss or when converting incompatible types 1
double d = 123.45;
int num = (int)d; // Explicit conversion (type casting)
Console.WriteLine(num); // Output: 123 (fractional part is truncated)
string str = "123";
int num = Convert.ToInt32(str); // Convert string to int
Console.WriteLine(num);
string str = "123";
int num = int.Parse(str); // String to int
5
Lecture No:03
Static And Instance Members of a Class In C# | C# Non-Static & Static Members
1. Static Members
Static members belong to the class itself rather than any instance of the class. Static
member has also acess the classs not need to create the object of the class.The static method and
variable you have define they have always same for all not change !important Under of static
method you have always use stactic variable not use Not static Or Intance variable.
class Example{
public static int Count = 0; // Static field
public static void DisplayCount() // Static method{
Console.WriteLine($"Count: {Count}");}
class Program{
static void Main(){
Example.Count = 5; // Accessing static member Not need to create the object
Example.DisplayCount(); // Calling static method
2. Instance Members
Instance members belong to specific instances (objects) of the class. Each instance has its own
copy of the instance members.means each obejct has own its value not same one to another.
class staticandInstance
{
public
6
int rollNo;
public string firstName;
public string lastName;
public void instanceMethod()
{
Console.WriteLine(firstName+" "+ lastName);
}
}
class Program
{
static void Main(string[] args)
{
staticandInstance fistobj = new staticandInstance();
fistobj.rollNo = 12;
fistobj.firstName = "Awias";
fistobj.lastName = "Saleem"; //output Awias Saleem:Amjad Akther 12 15
fistobj.instanceMethod();
staticandInstance secondobj=new staticandInstance();
secondobj.rollNo = 15;
secondobj.firstName = "Amjad";
secondobj.lastName = " Akther";
secondobj.instanceMethod();
Console.WriteLine(fistobj.rollNo+" "+secondobj.rollNo);
}
}
Difference:
Feature Static Member Instance Member
Belongs to Class Specific instance (object).
Access Through class name Through object reference.
Scope Shared across all objects Unique to each object.
Memory Allocation Allocated once for the class Allocated per instance.
Use Case Shared data or utility methods Object-specific data or behavior.
Lecture No:4
7
classes and objects
Classes:
A class is a blueprint for creating objects. It defines the properties (data) and methods (functions)
that an object of that class will have.
public class Car { // Fields (variables) of the class
public string Model;
public int Year;
// Constructor of the class
public Car(string model, int year) {
Model = model;
Year = year;
} // Method of the class
public void Drive() {
Console.WriteLine("The car is driving");
}}
Objects
An object is an instance of a class. When you create an object, you are creating an instance of a
class with specific values.
Lecture No:5
8
Constructor
In C#, a constructor is a special method that is used to initialize objects of a class. It has the
same name as the class and is called automatically when an object of the class is created.
Example 1: Default Constructor
//Default constructor
public Person() {
Name = "Unknown";
Console.WriteLine("Default constructor called.");
}
Example 2: Parameterized Constructor
// Parameterized constructor
public Person(string name, int age) {
Name = name;
Age = age;
}
Lecture No:6
9
Value Type And Reference Type In C# | Stack VS Heap In C#
|Struct VS Class
10
Refernce Type Class:
11
12
Lecture No:7
VAR and Dynamic Keywords In C#
1. var Keyword
The var keyword allows you to declare a variable whose type is determined at compile time
based on the value assigned to it. Once assigned, the type cannot be changed.
Static Typing:
var is statically typed, meaning the variable's type is known at compile time and cannot
change.
2. dynamic Keyword
The dynamic keyword is used to declare variables whose type is determined at runtime, and it
allows operations that bypass compile-time type checking.
13
Lecture No:8
Value type and Referance type:
14
15
Lecture No:26
Array VS ArrayList
1. Definition
Array: A fixed-size, strongly-typed collection of elements. It is part of the System
namespace.
ArrayList: A dynamic array that can resize itself dynamically and store elements of any
type. It is part of the System.Collections namespace.
2. Type-Safety
Array:
oStrongly typed: It can store only elements of a specific type.
ArrayList:
o Not strongly styped.can store different type of data.
Array Example: ArrayList Example:
int[] numbers = new int[3] ; ArrayList list = new ArrayList();
numbers[0] = 1; list.Add(1);
numbers[1] = 2; list.Add("Text");
numbers[2] = 3; list.Add(true);
// Fixed size // Dynamic size
16
17
Lecture No :27
Class Library In C#
A Class Library in C# is a collection of reusable classes, methods, interfaces, and other
functionalities compiled into a Dynamic Link Library (DLL) file.
A DLL is a library that contains code and data that can be used by more then one
program at the same time.
18
Lecture No:29
N-Tier Architecture
N-Tier Architecture, also known as Multitier Architecture, is a software design pattern
that separates an application into distinct layers or tiers.
Key Tiers in N-Tier Architecture
1. Presentation Tier (UI Layer)
o Purpose: Handles the user interface and user interactions.
2. Business Logic Tier (Application Layer)
Purpose: Contains the core application logic and rules.
3. Data Access Tier (DAL)
Purpose: Handles interaction with the database.
19
Lecture No :32
Index And Range In C#
Indexes
Indexes represent the position of an element in a collection. They can be used to access elements
from the start or the end of a collection.
// Accessing elements using regular index
Console.WriteLine(numbers[0]); // Output: 10
Console.WriteLine(numbers[2]); // Output: 30
// Accessing elements using ^ operator Hat Operator
Console.WriteLine(numbers[^1]); // Output: 50 (last element)
Console.WriteLine(numbers[^2]); // Output: 40 (second-to-last element)
Ranges
Ranges allow for slicing collections to retrieve subsets of data. The .. operator specifies a range.
1. startIndex..endIndex: Includes elements from startIndex up to (but not including)
endIndex
int[] numbers = { 10, 20, 30, 40, 50 }; // Slicing using ranges
int[] firstTwo = numbers[0..2]; // { 10, 20 }
int[] lastThree = numbers[^3..]; // { 30, 40, 50 }
int[] middle = numbers[1..^1]; // { 20, 30, 40}
20
Lecture No: 33
Global Usings | Static Usings | Alias With Using
Global usings were introduced in C# 10 to avoid repetitive using directives across
multiple files in a project. That is where use when you know that is my class I used many
time in our project you have have make a folder and the global class is defined.ya one
time you have defiend the global class is defined.
global using NamespaceName;
2. Static Usings
Static usings allow you to reference static members of a class without specifying the class name
each time.
That is used when you have not defined a buil-in vaiable many time is used that.like
Console is used Many time so you have in the top of defined the static variable of that.
using static System.Console;
class Program{
static void Main(){
WriteLine("Hello, World!"); // No need for Console.WriteLine}}
3. Alias With Using
The alias feature allows you to create shorter, more meaningful names for namespaces,
using IO = System.IO;
using MyList = System.Collections.Generic.List<int>;
class Program{
static void Main(){
IO.File.WriteAllText("example.txt", "Hello, File!");
MyList numbers = new MyList { 1, 2, 3, 4 };
Console.WriteLine(string.Join(", ", numbers)); // Output: 1, 2, 3, 4}}
21
Using Declaration is also used to free space object but I this case not using braces obj is
22
Lecture No:36
JWT(JSON WEB TOKEN)
JWT sa pala sessions use hota tha session ka masal ya tha ka wo ak server ka response
krta tha means user na apna credianls da dia then server as ko ak session create kr ka da dita tha
lakin next time server change ho jata tha means wo user ap login ni kr sakta tha ku ka server
change ho ga ha as li JWT intoduce krwa ga.
23
Structure of JWT | JWT Structure | Header | PayLoad | Signature |
24
Lecture No:37
Tuples In C#
In C#, Tuples are a lightweight data structure that can hold multiple items of different types.
They are commonly used to group related values together without creating a custom type or
class.
1. CREATING TUPLES (PRE-C# 7.0)
Tuples were created using the System.Tuple class:
var tuple = new Tuple<int, string, bool>(1, "Hello", true);
Console.WriteLine(tuple.Item1); // Output: 1
Console.WriteLine(tuple.Item2); // Output: Hello
Console.WriteLine(tuple.Item3);
2. TUPLE DECONSTRUCTION
You can deconstruct a tuple into separate variables:
var tuple = (Id: 2, Name: "Jane", IsActive: false);
// Deconstruct into variables
(int id, string name, bool isActive) = tuple;
Console.WriteLine(id); // Output: 2
Console.WriteLine(name); // Output: Jane
Console.WriteLine(isActive); // Output: False
Lecture No:38
25
New Data time types in C#
C# has introduced new date and time types over time to enhance precision, functionality, and
usability. Here are some newer or improved date and time types in C#, especially with
the .NET Core era and beyond:
1. DateOnly (Introduced in .NET 6)
Represents just the date without time information
var dateOnly = new DateOnly(2024, 11, 26); // Year, Month, Day
Console.WriteLine(dateOnly)
2. TimeOnly (Introduced in .NET 6)
Represents just the time without date information.
var timeOnly = new TimeOnly(14, 30); // Hour, Minute
Console.WriteLine(timeOnly); // Output: 2:30 PM
// Get current time
var currentTime = TimeOnly.FromDateTime(DateTime.Now);
Console.WriteLine(currentTime); // Output: Current Time
// Add hours or minutes
var later = currentTime.AddHours(2);
Console.WriteLine(later); // Output: Current Time + 2 hours
26
Lecture No 39:
File Scoped Namespaces In C#
27
Lecture No 40:
Static Local Functions In C# | Local Functions C#
But you have use Static varibable inside the staitic local method
28
29
Lecture No :41
30
Lecture No: 45
Arrrays and Collections
31
Summary
USE List<T> for most scenarios: it is fast, type-safe, and efficient.
USE LinkedList<T> when you need frequent insertions or deletions and are okay with
slower access.
AVOID ArrayList unless working with legacy code or when you need a non-generic
collection.
Comparison of ArrayList, List<T>, and LinkedList<T> in C#
Feature ArrayList List<T> LinkedList<T>
Namespace System.Collections System.Collections.Generic System.Collections.Generic
Type-Safe No Yes Yes
Access Speed Fast (index-based) Fast (index-based) Slow (sequential)
Insert/Delete Slow (shifting Slow (shifting needed) Fast (update links)
needed)
Resizable Yes Yes Yes
Boxing/ Yes (for value No No
Unboxing types)
Modern Usage Rare Frequently used Used for specific cases
The main difference between generic and non-generic collections is
that generic collections are strongly typed, while non-generic collections are
not:
Generic collections
These collections can only store a specific type of data, which ensures that the data is
always correct and the type is consistent throughout the program. Generic collections
are part of the System.Collections.Generic namespace. They are more flexible and
type-safe than non-generic collections, and they generally perform better.
Non-generic collections
These collections can store different types of data, which gives organizations more
freedom
Lecture No 46:
32
Collection Expressions In C#
Spread oprater are used copy to one collection to another.
33
Lecture No :48
lambda expressions
// Lambda expression Func<int, int> multiplyByTwo = x => x * 2;
// Wrapper method with a default parameter value
int Wrapper(int value = 5) => multiplyByTwo(value);
Console.WriteLine(Wrapper()); // Output: 10 (default 5 * 2)
Console.WriteLine(Wrapper(3))
34
Lectuer No 50:
REQUIRED MEMBERS in C#
REQUIRED MEMBERS in C# is a feature introduced in C# 11 that ensures specific object
properties or fields are initialized when an object is created. This feature is particularly useful in
improving DATA VALIDATION. THAT IS NOT USE FOR STATIC VARIABLE OR METHOD
public class Person{
public required string FirstName { get; set; }
public required string LastName { get; set; }
public int Age { get; set; } // Optional}
var person = new Person{
FirstName = "John", LastName = "Doe",
Age = 30 // This is optional };
35
Lectur No : 49 Delegates In C#
Delegates in C# are a type-safe way to define and use references to methods. They act as
pointers or references to methods and allow methods to be passed as parameters, assigned to
variables, and executed dynamically.
36
References
Last Name, F. M. (Year). Article Title. Journal Title, Pages From - To.
Last Name, F. M. (Year). Book Title. City Name: Publisher Name.
37
Footnotes
1
[Add footnotes, if any, on their own page following references. For APA formatting requirements, it’s e
38
Tables
Table 1
[Table Title]
Column Head Column Head Column Head Column Head Column Head
Row Head 123 123 123 123
Row Head 456 456 456 456
Row Head 789 789 789 789
Row Head 123 123 123 123
Row Head 456 456 456 456
Row Head 789 789 789 789
Note:
[Place all tables for your paper in a tables section, following references (and, if applicable, footnotes). Sta
39
Figures title:
0
Category 1 Category 2 Category 3 Category 4
Series 1 Series 2 Series 3
Figure 1.
[Include all figures in their own section, following references (and footnotes and tables, if applicable).
For more information about all elements of APA formatting, please consult the APA Style
Manual, 6th Edition.
40