SlideShare a Scribd company logo
C#
Presented By: K P Verma
C# Version
Version .Net Framework Visual Studio Important Features
C# 1.0 .NET Framework
1.0/1.1
Visual Studio .NET
2002
Basic features
C# 2.0 .NET Framework
2.0
Visual Studio 2005 Generics, Partial types, Anonymous methods, Iterators, Nullable
types, Private setters(properties), Delegates, Covariance and
Contra-variance,
Static classes
C# 8.0 .NET Core 3.0 Visual Studio 2019 Readonly members, Default interface methods, Using
declarations, Static local functions, Disposable ref structs,
Nullable reference types, Indices and ranges, Null-coalescing
assignment
C# 9.0 . NET 5.0 Visual Studio 2019 Records, Init-only properties, Top-level statements,
Init accessors and readonly fields, With-expressions, Value-based
equality, Lambda discard parameters
C# 10.0 .NET 6.0 Visual Studio 2022 Record structs, Global using directives, File-scoped namespace
declaration, Extended Proptery Patterns, Null Parameter
Checking, Constant interpolated strings
C# Version
Version .Net Framework Visual Studio Important Features
C# 11 .Net 7 Newlines in string interpolation expressions, File-local types
Required members, Auto-default structs, Numeric IntPtr
ref fields and scoped ref
C# 12 .Net 8 Primary constructors- You can create primary constructors in any
class or struct type.
Inline arrays - Inline arrays enable you to create an array of fixed
size in a struct type.
Optional parameters in lambda expressions - You can define
default values for parameters on lambda expressions.
ref readonly parameters - ref readonly parameters enables more
clarity for APIs that might be using ref parameters or in
parameters.
Alias any type - You can use the using alias directive to alias any
type, not just named types.
Experimental attribute - Indicate an experimental feature.
Keywords
• Modifier Keywords: abstract, async, const, event, extern, new, override, partial,
readonly, sealed, static, unsafe, virtual, volatile
• Access Modifier: public, private, protected, internal
• Statement Keyword: if, else, switch, case, do, for, foreach, in, while, break, continue,
default, goto, return, yield, throw, try, catch, finally, checked, unchecked, fixed, lock
• Method Parameter Keywords: params, ref, out
• Namespace Keywords: using, .operator, ::operator, extern, alias
• Operator Keywords: as, await, is, new, sizeof, typeof, stackalloc, checked, unchecked
• Access Keywords: base, this
• Literal Keywords: null, false, true, value, void
• Type Keywords: bool, byte, char, class, decimal, double, enum, float, int, long, sbyte,
short, string, struct, uint, ulong, ushort
• Contextual Keyword: add, var, dynamic, global, set, value
OOPS
Class
• class is a group of similar objects. It is a template from which objects are created. It can have
fields, methods, constructors, etc.
• Object is an instance of a class. All the members of the class can be accessed through the object.
Student s1 = new Student();//creating an object of Student
• object is an entity that has a state and behavior. Here, state means data, and behavior means
functionality.
public class Student
{
public int id;
public String name;
}
class TestStudent{
public static void Main(string[] args)
{
Student s1 = new Student();
s1.id = 101;
s1.name = "KP";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
Constructor
• A constructor is a special method of the class which gets automatically invoked
whenever an instance of the class is created.
• It is used to assign initial values to the data members of the same class.
• The constructor of a class must have the same name as the class name in which
it resides.
• A constructor can not be abstract, final, and Synchronized.
• Within a class, you can create only one static constructor.
• A constructor doesn’t have any return type, not even void.
• A static constructor cannot be a parameterized constructor.
• A class can have any number of constructors with different types of arguments.
• Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
• Types of Constructor: Default Constructor, Parameterized Constructor, Copy
Constructor, Private Constructor, Static Constructor
Default Constructor
• A constructor with no parameters is called a default constructor.
• A default constructor has every instance of the class to be initialized to the
same values.
• The default constructor initializes all numeric fields to zero and all string
and object fields to null inside a class.
public class Employee
{
public Employee() // Default Constructor
{
Console.WriteLine("Default Constructor Invoked");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}
Parameterized Constructor
• A constructor having at least one parameter is called as parameterized
constructor.
• It can initialize each instance of the class to different values.
Copy Constructor
• This constructor creates an object by copying variables from another object.
• Its main use is to initialize a new instance to the values of an existing
instance.
• If a Parameterized constructor uses a parameter as the object itself is called
a copy constructor.
• Generally, c# won’t provide a copy constructor for objects but we can
implement ourselves based on our requirements.
public User(User user) // Copy Constructor
{
name = user.name;
location = user.location;
}
Private Constructor
• If a constructor is created with a private specifier is known as a Private
Constructor.
• Private Constructors are used to restrict the creation of an instance for that
particular constructor from another class.
• If a class contains one or more private constructors and no public
constructors, then the other classes are not allowed to create an instance
for that particular class except nested classes.
• It is the implementation of a singleton class pattern.
• Use a private constructor when we have only static members.
private Employee() // private Constructor
{
Console.WriteLine("private Constructor Invoked");
}
Static Constructor
• Static Constructor has to be invoked only once in the class irrespective of the
number of class instances.
• A static constructor can only access static members. It cannot contain or access
instance members.
• It is used to perform a particular action only once throughout the application.
• A static constructor is initialized static fields or data of the class and is to be
executed only once.
• It can’t be called directly.
• When it is executing then the user has no control as it will be invoked by CLR.
• It does not take access modifiers or any parameters.
• It is called automatically to initialize the class before the first instance is created.
• only one static constructor is allowed to create.
static User()
{
Console.WriteLine("I am Static Constructor");
}
Constructor Chaining
• Constructor Chaining: It is an approach to invoke one constructor from
another constructor.
• To achieve constructor chaining we need to use this keyword after our
constructor definition.
• Constructor Overloading: C# supports the overloading of constructors,
which means we can have constructors with different sets of parameters.
Destructor
• A destructor works opposite to the constructor, It destructs the objects of classes when
they are no longer needed.
• It can be defined only once in a class, not in Structures.
• An instance variable or an object is eligible for destruction when it is no longer reachable.
• Destructor cannot have parameters. Moreover, modifiers can't be applied to destructors.
• A Destructor is unique to its class i.e. there cannot be more than one destructor in a class.
• A Destructor has no return type and has exactly the same name as the class name
(Including the same case).
• It is represented by using a tilde (~) operator prefixed to its name.
• It cannot be overloaded or inherited.
• It is called when the program exits.
• Internally, Destructor called the Finalize method on the base class of object by the .NET
Framework’s Garbage collector. therefore programmer has no control as to when to
invoke the destructor.
static keyword
• static is a keyword and modifier that belongs to the type not instance. So instance is not
required to access the static members.
• When a member is declared static, it can be accessed with the name of its class directly.
• It applies to fields, methods, constructors, classes, properties, operators, or events.
• Memory efficient: Now we don't need to create an instance for accessing the static members, so
it saves memory. Moreover, it belongs to the type, so it will not get memory each time when an
instance is created.
• Shared Memory: The instance of the class will contain a separate copy of all instance fields so the
memory consumption will increase automatically, but if we use a static modifier there is only one
copy of each field so automatically the memory will be managed efficiently.
⮚ Limitations:
• Indexers, destructors, finalizers, and types cannot be static.
• static member is not referenced through an instance.
• It is not allowed to use this to reference static methods or property accessors.
• If a static keyword is used with the class, then the static class always contains static members.
static keyword
● Static Class
• It is not allowed to create objects of the static class.
• All the members of a static class must be static; otherwise the compiler will give an error.
• Static classes are sealed, which means one cannot inherit a static class from another class.
• A static class cannot contain instance members and constructors.
⮚ Static Variable
• When a variable is declared as static, then a single copy of the variable is created and shared among all objects at
the class level.
• Static variables are accessed with the name of the class, they do not require any object for access.
⮚ Static Method
• A static method can access static and non-static fields but cannot access or call non-static variables unless they
are explicitly passed as parameters.
• static fields are directly accessed by the static method with a class name whereas non-static fields require objects.
• Static methods can be overloaded but cannot be overridden.
⮚ Static Constructor
• Static Constructor is invoked only once (implicitly) in the class and it has been invoked during the creation of the
first reference to a static member in the class.
• A static constructor is initialized static fields or data of the class and is to be executed only once.
structs
• A structure a collection of variables of different data types under a single unit.
• Structs can be used to hold small data that is not intended to be modified or inherited after the
creation of the structure.
• Structs are used for lightweight objects (like Color, rectangles) and defined by the struct keyword.
• Unlike class, structs are value types data structures rather than reference types
• Struct doesn't support inheritance. But it can implement interfaces.
• During struct declaration, the fields cannot be initialized unless they are defined as const or static.
• Structures can include fields, properties, member functions, operators, constructors (parameterized
& static), events, indexers, constants, operators, nested types, and even other structure types.
• Structs cannot include default constructors or destructors but they can contain parameterized
constructors.
• The default modifier is internal for the struct and its members.
• A structure can be instantiated with or without using a new keyword.
• Struct members cannot be specified as abstract, sealed, virtual, or protected.
• If you declare a variable of struct type without using a new keyword, it does not call any constructor,
so all the members remain unassigned. Therefore, you must assign values to each member before
accessing them, otherwise, it will give a compile-time error.
Class vs structs
Class Structs
reference types value types
contain constructors or destructor contain only parameterized constructor and static
constructor
Support inheritance Does not support inheritance
All the reference types are allocated on heap memory. All the value types are allocated on stack memory.
Classes used new keyword for creating instances. Struct can create an instance, with or without a new keyword.
The data member of a class can be protected. The data member of struct can’t be protected.
Function member of the class can be virtual or abstract. Function member of the struct cannot be virtual or abstract.
limitless features and generally used in large programs. limited features and used in small programs
enum
• Enum is also known as enumeration.
• It is used to store a set of named constants such as season, days, month, size etc. The enum
constants are also known as enumerators.
• Enum can be declared within or outside class and structs.
• Enum constants have default values that start from 0 and increment to one by one. But we can
change the default value.
• Enum has a fixed set of constants
• Enum improves type safety
• Enum can be traversed
• Explicit casting is required to convert from an enum type to its underlying integral type.
Partial Classes and Methods
• To split the functionality of class, structure, interface or method over multiple files we need to use
partial keywords and all files must be available at compile time to form the final type.
• The partial modifier can only appear immediately before the keywords class, struct or interface.
• All the partial class definitions must be in the same assembly and namespace.
• All the parts must have the same accessibility like public or private, etc.
• If any part is declared abstract, sealed or base type then the whole class is declared of the same
type.
• Different parts can have different base types so the final class will inherit all the base types.
• The Partial modifier can only appear immediately before the keywords class, struct, or interface.
• Nested partial types are allowed.
⮚ Partial Method
• Partial methods must use the partial keyword and must return void.
• Partial methods can have in or ref but not out parameters.
• Partial methods are implicitly private methods, so cannot be virtual.
• Partial methods can be static methods.
• Partial methods can be generic.
Extension Method
• Extension methods are additional custom methods which were originally not included with the
class.
• Extension methods can be added to custom, .NET Framework or third party classes, structs or
interfaces.
• The first parameter of the extension method must be of the type for which the extension method is
applicable, preceded by the this keyword.
• Extension methods can be used anywhere in the application by including the namespace of the
extension method.
Delegates, Events & Anonymous
Delegates
• Delegate is a reference type variable that holds a reference to a method/function with a specific
parameter list and return type.
• It is declared by the delegate keyword and acts as a type-safe function pointer.
• Provides a good way to encapsulate the methods.
• Delegate is the reference type data type that defines the signature.
• Delegate type variable can refer to any method with the same signature as the delegate.
• Syntax: [access modifier] delegate [return type] [delegate name]([parameters])
• A target method's signature must match with delegate signature.
• Delegates can be invoke like a normal function or Invoke() method.
• Delegate is used to declare an event and anonymous methods in C#.
• Delegates are mainly used in implementing the call-back methods and events.
• Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in
certain contexts. Sometimes, these features together are known as anonymous functions.
• There are three steps involved while working with delegates:
1. Declare a delegate
2. Create an instance and reference a method
3. Invoke a delegate
Multicast Delegates
• Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast
Delegate). It helps the user to point more than one method in a single call.
• If a multicast delegate returns a value then it returns the value from the last assigned target
method.
• Delegates are combined and when you call a delegate then a complete list of methods is called.
• All methods are called in First in First Out(FIFO) order.
• ‘+’ or ‘+=’ Operator is used to add the methods to delegates.
• ‘–’ or ‘-=’ Operator is used to remove the methods from the delegates list.
• Limitation
• Multicasting of delegate should have a return type of Void otherwise it will throw a runtime
exception.
• Multicasting of delegate will return the value only from the last method added in the multicast.
Although, the other methods will be executed successfully.
Advantages and Use of Delegates
• Function Pointers: Delegates allow you to treat methods as objects, enabling you to pass methods as
parameters to other methods, store them in data structures, or return them from methods. This is
similar to function pointers in languages like C and C++.
• Event Handling: It is commonly used in event handling in C# to implement the observer pattern.
Events in C# are based on delegates, and they allow objects to subscribe to and receive notifications
when certain actions or events occur.
• Decoupling: Delegates help in decoupling the calling code from the implementation of the method
being called. This promotes separation of concerns and makes the code more modular and
maintainable.
• Dynamic Behavior: Delegates provide a way to achieve dynamic behavior in your code by allowing
you to change the method being called at runtime. This can be useful in scenarios where you
need to switch between different implementations of a method based on certain conditions.
• Callback Functions: Delegates are often used to implement callback functions where a method can
call back to a method defined in another class or part of the codebase.
• Multi-cast Delegates: Delegates in C# support multi-cast functionality, which means you can
combine multiple methods into a single delegate instance. When you invoke a multi-cast delegate, all
the methods it points to are called in the order they were added.
• Anonymous Methods and Lambda Expressions: Delegates work well with anonymous methods and
lambda expressions, allowing for more concise and readable code, especially for event handling and
asynchronous programming.
Func & Action Delegate
• Func and Action is a generic delegate included in the System namespace.
• Func and Action is built-in delegate type.
• Func and Action delegate type can be used with an anonymous method or lambda expression.
Func
• Func can have zero to 16 input parameters of different types and one out parameter. The last
parameter is considered as an out parameter.
• Func delegate type must return a value.
• Func delegate does not allow ref and out parameters.
Action
• Action delegate is same as func delegate except that it does not return anything. Return type must
be void.
• Action delegate can have 0 to 16 input parameters of different types.
Advantages of Func and Action
• Easy and quick to define delegates.
• Makes code short.
• Compatible type throughout the application.
Predicate Delegate
• Predicate is the delegate like Func and Action delegates.
• It represents a method containing a set of criteria and checks whether the passed
parameter meets those criteria.
• A predicate delegate methods must take one input parameter and return a boolean - true or
false.
• Anonymous method and Lambda expression can be assigned to the predicate delegate.
Anonymous Types
• Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single
object without having to explicitly define a type first.
• The type name is generated by the compiler and is not available at the source code level. The type of
each property is inferred by the compiler.
• an anonymous type is a type (class) without any name that can contain public read-only properties
only. It cannot contain other members, such as fields, methods, events, etc.
• var student = new { Id = 1, FirstName = "James", LastName = "Bond" };
• The properties of anonymous types are read-only and cannot be initialized with a null, anonymous
function, or a pointer type.
• An anonymous type will always be local to the method where it is defined. It cannot be returned from
the method.
• an anonymous type can be passed to the method as object type parameter, but it is not
recommended.
• If you need to pass it to another method, then use struct or class instead of an anonymous type.
• Mostly, anonymous types are created using the Select clause of a LINQ queries to return a subset of
the properties from each object in the collection.
• Anonymous types contain one or more public read-only properties.
• To create an anonymous type using the new operator with an object initializer syntax.
• The implicitly typed variable- var is used to hold the reference of anonymous types.
• The properties can be accessed using dot (.) notation, same as object properties. However, you
cannot change the values of properties as they are read-only.
• This can be nested.
Anonymous Method
• An anonymous method is a method without a name.
• It is useful when the user wants to create an inline method and also wants to pass parameter in the
anonymous method like other methods.
• An Anonymous method is defined using the delegate keyword and must be assign this method to a
variable of the delegate type.
• This method is also known as inline delegate.
• Using this method you can create a delegate object without writing separate methods.
• This method can access variable present in the outer method like as Outer variables.
• This method can be pass to another method which accepts delegate as a parameter.
• The anonymous-method-block means the scope of the parameters in the anonymous method.
• You can also use an anonymous method as an event handler.
• Limitations
• An anonymous method does not contain jump statements like goto, break, or continue.
• An anonymous method does not access unsafe code.
• An anonymous method does not access in, ref, and out parameter of the outer scope.
• You can not use an anonymous method to the left side of the is operator.
Events
• An event is a wrapper around a delegate. It depends on the delegate.
• Use "event" keyword with delegate type variable to declare an event.
• Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events.
• The publisher class raises an event, and the subscriber class registers for an event and provides
the event-handler method.
• Name the method which raises an event prefixed with "On" with the event name.
• The signature of the handler method must match the delegate signature.
• Register with an event using the += operator. Unsubscribe it using the -= operator. Cannot use
the = operator.
• Pass event data using EventHandler<TEventArgs>.
• Derive EventArgs base class to create custom event data class.
• Events can be declared static, virtual, sealed, and abstract.
• An Interface can include the event as a member.
• Event handlers are invoked synchronously if there are multiple subscribers.
Delegate vs Events
Delegate Events
A delegate is declared using the delegate keyword. An event is declared using the event keyword.
Delegate is a function pointer. It holds the reference
of one or more methods at runtime.
The event is a notification mechanism that depends on delegates
Delegate is independent and not dependent on
events.
An event is dependent on a delegate and cannot be created without delegates.
Event is a wrapper around delegate instance to prevent users of the delegate from
resetting the delegate and its invocation list and only allows adding or removing
targets from the invocation list.
Delegate includes Combine() and Remove() methods
to add methods to the invocation list.
EventInfo class inspect events and to hook up event handlers that include
methods AddEventHandler() and RemoveEventHandler() methods to add and
remove methods to invocation list, respectively.
A delegate can be passed as a method parameter. An event is raised but cannot be passed as a method parameter.
= operator is used to assigning a single method, and
+= operator is used to assign multiple methods to a
delegate.
= operator cannot be used with events, and only += and -= operator can be used
with an event that adds or remove event handler. These methods internally call
AddEventHandler and RemoveEventHandler methods.
Generics
Generics
• Generic means the general form, means not specific to a particular data type.
• Generic can be classes, interfaces, abstract classes, fields, methods, static methods, properties,
events, delegates, and operators using the type parameter and without the specific data type.
• Generics are type-safe. You get compile-time errors if you try to use a different data type than the
one specified in the definition.
• Generic has a performance advantage because it removes the possibilities of boxing and unboxing.
• A generic class increases the reusability. The more type parameters mean more reusable it
becomes. However, too much generalization makes code difficult to understand and maintain.
• A generic class can be a base class to other generic or non-generic classes or abstract classes.
• A generic class can be derived from other generic or non-generic interfaces, classes, or abstract
classes.
• A generic class can include generic fields. However, it cannot be initialized.
Generics Constraints
• C# allows to use constraints to restrict client code to specify certain types while instantiating
generic types.
• It will give a compile-time error if you try to instantiate a generic type using a type that is not
allowed by the specified constraints.
• can specify one or more constraints on the generic type using the where clause after the generic
type name.
Constrains The type argument must be
class any class, interface, delegate, or array type.
class? a nullable or non-nullable class, interface, delegate, or array type.
struct non-nullable value types such as primitive data types int, char, bool, float, etc.
new() a reference type which has a public parameterless constructor. It cannot be combined with struct and unmanaged
constraints.
notnull non-nullable reference types or value types. If not, then the compiler generates a warning instead of an error.
unmanaged non-nullable unmanged types.
base class name or derive from the specified base class. The Object, Array, ValueType classes are disallowed as a base class constraint. The Enum,
Delegate, MulticastDelegate are disallowed as base class constraint before C# 7.3.
Garbage Collection
Garbage Collection
• Garbage collector is responsible for managing memory and automatically freeing up memory that is
no longer being used by the application.
• It works by periodically scanning the application’s memory to determine which objects are still
being used and which are no longer needed.
• Objects that are no longer being used are marked for garbage collection, and their memory is freed
up automatically by the garbage collector.
Feature of Garbage Collection
• Automatic memory management: With the garbage collector, developers don’t need to
worry about manually allocating or freeing up memory. The garbage collector takes care of
memory management automatically, which can help reduce the risk of memory leaks and
other issues.
• Low impact on application performance: The garbage collector runs in the background
and typically has a low impact on application performance. However, in some cases, garbage
collection can cause brief pauses or slowdowns in the application, particularly when large
amounts of memory need to be freed up at once.
• Generation-based collection: The garbage collector in C# uses a generation-based
approach to memory management. Objects are initially allocated in a “young” generation and
are moved to an “old” generation if they survive multiple garbage collection cycles. This
approach helps reduce the amount of time required for garbage collection, as most objects
are collected in the young generation.
• Finalization: The garbage collector also provides support for finalization, which is a process
that allows objects to perform cleanup tasks before they are destroyed. Objects with finalizers
are moved to a separate finalization queue, which is processed by the garbage collector after
all other objects have been collected.
Phases in Garbage Collection
1. Marking Phase: A list of all the live objects is
created during the marking phase. This is done by
following the references from all the root objects. All
of the objects that are not on the list of live objects
are potentially deleted from the heap memory.
2. Relocating Phase: The references of all the objects
that were on the list of all the live objects are
updated in the relocating phase so that they point to
the new location where the objects will be relocated
to in the compacting phase.
3. Compacting Phase: The heap gets compacted in
the compacting phase as the space occupied by the
dead objects is released and the live objects
remaining are moved. All the live objects that remain
after the garbage collection are moved towards the
older end of the heap memory in their original order.
Generations in Garbage Collection
• The heap memory is organized into 3 generations so that various
objects with different lifetimes can be handled appropriately during
garbage collection. The memory to each Generation will be given by
the (CLR) depending on the project size. Internally, Optimization
Engine will call the Collection Method to select which objects will go
into which Generation.
• Generation 0 : All the short-lived objects such as temporary
variables are contained in the generation 0 of the heap memory. All
the newly allocated objects are also generation 0 objects implicitly
unless they are large objects. In general, the frequency of garbage
collection is the highest in generation 0.
• Generation 1 : If space occupied by some generation 0 objects that
are not released in a garbage collection run, then these objects get
moved to generation 1. The objects in this generation are a sort of
buffer between the short-lived objects in generation 0 and the long-
lived objects in generation 2.
• Generation 2 : If space occupied by some generation 1 objects that
are not released in the next garbage collection run, then these
objects get moved to generation 2. The objects in generation 2 are
long lived such as static objects as they remain in the heap memory
for the whole process duration.
• Memory Allocation : Generation 2 > Generation 1 > Generation 0
Methods in Garbage Collection
• GC.GetGeneration() : This method returns the generation number of the target object. It
requires a single parameter i.e. the target object for which the generation number is required.
• GC.GetTotalMemory() : This method returns the number of bytes that are allocated in the
system. It requires a single boolean parameter where true means that the method waits for the
occurrence of garbage collection before returning and false means the opposite.
• GC.Collect() : Garbage collection can be forced in the system using the GC.Collect() method. This
method requires a single parameter i.e. number of the oldest generation for which garbage
collection occurs.
• GC.SuppressFinalize() : This system method is designed to prevent calling the finalizer on the
specified object by CLR.
Benefit of Garbage Collection
• Garbage Collection succeeds in allocating objects efficiently on the heap memory using the
generations of garbage collection.
• Manual freeing of memory is not needed as garbage collection automatically releases the
memory space after it is no longer required.
• Garbage collection handles memory allocation safely so that no object uses the contents of
another object mistakenly.
• The constructors of newly created objects do not have to initialize all the data fields as garbage
collection clears the memory of objects that were previously released.
Concurrent Garbage Collection
• Concurrent garbage collection is performed on a dedicated thread.
• This enables threads to run concurrently with a dedicated thread that performs the garbage
collection for most of the duration of the collection.
• This option affects only garbage collections in generation 2; generations 0 and 1 are always non-
concurrent because they finish fast.
Exception Handling
throw vs throw ex vs throw new Exception()
 Stack Trace Preservation
• throw: Preserves the original stack trace, providing complete information about where the
exception originated.
• throw ex: Resets the stack trace, which can make it harder to debug the root cause of the
exception.
• throw new Exception("An error occurred", ex): Provides additional context with a new
exception message while preserving the original exception as an inner exception.
 Use Cases
• throw: Use this when you want to maintain the original exception context and stack trace, which is
almost always the preferred approach.
• throw ex: Use this sparingly, and only when you need to add additional information to the
exception before rethrowing it.
• throw new Exception("An error occurred", ex): Use this when you want to add more context
to the exception while retaining the original exception details.
Multithreading
Main Thread
 Multithreading refers to the capability to create and manage multiple threads within a single
process. A thread is the smallest unit of execution within a process, and multiple threads can run
concurrently, sharing the same resources of the parent process but executing different code paths.
• Ideal for CPU-bound tasks that can be parallelized, such as image processing, video encoding, or
mathematical computations, as well as scenarios requiring responsive user interfaces.
 Main Thread: When a C# program starts up, one thread begins running immediately. This is
usually called the main thread of our program.
• It is the first thread under which all child thread created.
• Often, it must be the last thread to finish execution because it performs various shutdown actions.
• The main thread works just like other thread but it starts automatically, you need not to require
any Start() method to start the execution of the main thread.
• CurrentThread property : to access the main thread or inside the main thread to get the
reference of the main thread. Thread.CurrentThread
• Deadlock using Main Thread : a deadlock can be created by just using Main thread.
Thread.CurrentThread.Join();
• The statement “Thread.currentThread().join()”, will tell the Main thread to wait for this
thread(i.e. wait for itself) to die. Thus the Main thread waits for itself to die, which is nothing but a
deadlock.
Thread Life Cycle
• Thread Life Cycle states: Unstarted, Runnable (Ready to run), Running, Not Runnable (Sleep(),
Wait(), Due to I/O request, Suspend()), Dead (Terminated)
Thread Class
• A multi-threading system is built upon the Thread class, which encapsulates the execution of
threads.
• This class contains several methods and properties which helps in managing and creating threads
and this class is defined under System.Threading namespace.
• Thread class is used to create threads.
• Using this can be created foreground and background thread.
• Thread class allows to set the priority of a thread.
• It also provides the current state of a thread.
• It provides the reference of the current executing thread.
• It is a sealed class, so it cannot be inherited.
• Constructor: Thread(ParameterizedThreadStart), Thread(ParameterizedThreadStart, Int32), Thread(ThreadStart),
Thread(ThreadStart, Int32)
• Properties: CurrentContext, CurrentCulture, CurrentThread, IsAlive, IsBackground, IsThreadPoolThread, Name,
Priority, ThreadState
• Method: Abort(), Equals(Object), Finalize(), GetType(), Interrupt(), Join(), ResetAbort(), Resume(), Sleep(), SpinWait(Int32),
Start(), Suspend(), ToString(), Yield()
Thread Types
 Foreground Threads: They prevent the application from terminating until all foreground threads have completed
their tasks.
• A foreground thread can be created by calling the Thread.Start() method.
• When an application starts, it automatically creates a foreground thread, i.e. main thread of the application.
• All threads generated by creating and starting a new Thread object are by default foreground threads. However, you
can change the type of a thread by setting the IsBackground property of the thread.
• Foreground threads are useful when need to perform a task that is critical to the operation of the
application and must be completed before the application can terminate.
• Ex.- a foreground thread might be used to update the user interface or to perform important calculations.
• Foreground thread does not care whether the main thread is alive or not, it completes only when it
finishes its assigned work.
 Background Threads: They do not prevent the application from terminating, even if they are still running.
• A background thread can be created by calling the Thread.Start() method and then setting the IsBackground
property of the thread to true before starting it.
• Background threads are useful when need to perform a task that is not critical to the operation of the application
and can be terminated if the application needs to shut down.
• Ex.- a background thread might be used to download a large file or to perform periodic updates to a database.
• A thread which leaves its process when the Main method leaves its process, these types of the thread
are known as the background threads.
• All threads that enter the managed execution environment from unmanaged code are marked as background
threads.
Thread Join
 Thread.Join() : The Join method of the Thread class waits for the thread to complete its execution
before continuing with the execution of the calling thread.
• This method blocks the calling thread until the target thread has completed its execution.
• Join() Overload : Join(), Join(Int32) , Join(TimeSpan)
 Task.WaitAll(): The WaitAll method of the Task class waits for all the specified tasks to complete
before continuing with the execution of the calling thread.
• This method blocks the calling thread until all the specified tasks have completed their execution.
Async & Await
Asynchronous Programming
• Asynchronous Programming: Using asynchronous programming indicates that a method can
execute without waiting for another method to complete. Using async and await, we can run the
methods above parallelly.
• An async keyword is a method that performs asynchronous tasks such as fetching data from a
database, reading a file, etc, they can be marked as “async”.
• await keyword making “await” to a statement means suspending the execution of the async
method it is residing in until the asynchronous task completes.
• After suspension, the control goes back to the caller method. Once the task completes, the control
comes back to the states where await is mentioned and executes the remaining statements in the
enclosing method.
• await can only be used inside an async method.
• If a method which uses async modifier does not contain await expression, executes
synchronously.
• the async method cannot use ref or out parameters.
• Return type: Task, Task<TResult>, Void (for event handlers), Tasks.ValueTask<TResult>
• Use Case: I/O-bound operations (like reading from a file, fetching data from the web, or querying a
database), network communication, file I/O, and database access, where non-blocking execution
and scalability are essential.
Multithreading vs Asynchronous vs Parallel Programming
 Multithreading focuses on allowing multiple threads to operate concurrently, often within a single
process, to maximize resource usage and maintain responsiveness. So, Multithreading is a process that
contains multiple threads within a single process. Here, each thread performs different activities.
• Multithreading involves the concurrent execution of multiple threads within a process.
• Effective in scenarios where parallelism can significantly enhance performance.
• Ideal for CPU-bound tasks that can be parallelized, such as image processing, video encoding, or
mathematical computations, as well as scenarios requiring responsive user interfaces.
 Asynchronous Programming focuses on non-blocking operations, especially for I/O-bound tasks,
ensuring responsiveness and scalability without waiting for each to complete.
• Improved efficiency by avoiding idle time during I/O operations.
• Well-suited for I/O-bound operations, such as reading from or writing to databases or making API calls.
network communication, file I/O, and database access, where non-blocking execution and scalability are
essential.
 Parallel Programming focuses on splitting tasks to run simultaneously on multiple processors or cores
to reduce total computation time for CPU-bound operations.
• In this case, it will use multiple processors to execute different parts of a task; each processor has
multiple threads that can execute the application code.
Thanks for the Attention...
Happy Coding...

More Related Content

PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
PPTX
Prototype design patterns
PDF
Angular Advanced Routing
PPTX
Omnisearch in AEM 6.2 - Search All the Things
PPTX
Package in Java
ODP
Spring User Guide
PPTX
Laravel Presentation
ODP
Introduction to Spring Framework and Spring IoC
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Prototype design patterns
Angular Advanced Routing
Omnisearch in AEM 6.2 - Search All the Things
Package in Java
Spring User Guide
Laravel Presentation
Introduction to Spring Framework and Spring IoC

What's hot (20)

PPTX
Java Comments | Java course
PDF
Angular Directives
PPTX
React introduction
PPTX
Java constructors
PPTX
Introduction to Spring Framework
PDF
JUnit & Mockito, first steps
PPT
Pl sql guide
PDF
Assignment#02
PDF
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
PPTX
Factory Method Pattern
PPTX
Windows form application - C# Training
PPTX
Inheritance in OOPs with java
ODP
Protocol Buffers
PPTX
Java literals
PPTX
Spring data jpa
PPTX
Introduce yourself to java 17
PPTX
object oriented programming(PYTHON)
PPTX
This keyword in java
PPTX
Spring Boot
PPTX
OOP-Advanced Programming with c++
Java Comments | Java course
Angular Directives
React introduction
Java constructors
Introduction to Spring Framework
JUnit & Mockito, first steps
Pl sql guide
Assignment#02
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Factory Method Pattern
Windows form application - C# Training
Inheritance in OOPs with java
Protocol Buffers
Java literals
Spring data jpa
Introduce yourself to java 17
object oriented programming(PYTHON)
This keyword in java
Spring Boot
OOP-Advanced Programming with c++
Ad

Similar to Quick Interview Preparation for C# All Concepts (20)

PPTX
OCP Java (OCPJP) 8 Exam Quick Reference Card
PPTX
basic concepts of object oriented in python
PPTX
PPTX
CONSTRUCTORS.pptx
PPTX
class as the basis.pptx
PPTX
C# classes objects
PPTX
C# structure
PPTX
Javasession8
PPTX
A constructor in Java is a special method that is used to initialize objects
PPT
Java inheritance concept, interface, objects, extends
PPT
04 inheritance
PPT
04_inheritance power point presentation.
PPTX
Creational Design Patterns.pptx
PPTX
Object-oriented programming 3.pptx
PPTX
Better Understanding OOP using C#
PPT
inheritance
PPTX
Design p atterns
PDF
2 BytesC++ course_2014_c6_ constructors and other tools
PPT
VIRTUAL FUNCTIONS c++ -POLYMORPHISM.ppt
PDF
‏‏oop lecture 2 taiz univercity object programming.pdf
OCP Java (OCPJP) 8 Exam Quick Reference Card
basic concepts of object oriented in python
CONSTRUCTORS.pptx
class as the basis.pptx
C# classes objects
C# structure
Javasession8
A constructor in Java is a special method that is used to initialize objects
Java inheritance concept, interface, objects, extends
04 inheritance
04_inheritance power point presentation.
Creational Design Patterns.pptx
Object-oriented programming 3.pptx
Better Understanding OOP using C#
inheritance
Design p atterns
2 BytesC++ course_2014_c6_ constructors and other tools
VIRTUAL FUNCTIONS c++ -POLYMORPHISM.ppt
‏‏oop lecture 2 taiz univercity object programming.pdf
Ad

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Spectroscopy.pptx food analysis technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Spectroscopy.pptx food analysis technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Understanding_Digital_Forensics_Presentation.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
The AUB Centre for AI in Media Proposal.docx
MIND Revenue Release Quarter 2 2025 Press Release
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
MYSQL Presentation for SQL database connectivity
Chapter 3 Spatial Domain Image Processing.pdf
Machine learning based COVID-19 study performance prediction
Programs and apps: productivity, graphics, security and other tools
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Per capita expenditure prediction using model stacking based on satellite ima...
Advanced methodologies resolving dimensionality complications for autism neur...
Teaching material agriculture food technology

Quick Interview Preparation for C# All Concepts

  • 2. C# Version Version .Net Framework Visual Studio Important Features C# 1.0 .NET Framework 1.0/1.1 Visual Studio .NET 2002 Basic features C# 2.0 .NET Framework 2.0 Visual Studio 2005 Generics, Partial types, Anonymous methods, Iterators, Nullable types, Private setters(properties), Delegates, Covariance and Contra-variance, Static classes C# 8.0 .NET Core 3.0 Visual Studio 2019 Readonly members, Default interface methods, Using declarations, Static local functions, Disposable ref structs, Nullable reference types, Indices and ranges, Null-coalescing assignment C# 9.0 . NET 5.0 Visual Studio 2019 Records, Init-only properties, Top-level statements, Init accessors and readonly fields, With-expressions, Value-based equality, Lambda discard parameters C# 10.0 .NET 6.0 Visual Studio 2022 Record structs, Global using directives, File-scoped namespace declaration, Extended Proptery Patterns, Null Parameter Checking, Constant interpolated strings
  • 3. C# Version Version .Net Framework Visual Studio Important Features C# 11 .Net 7 Newlines in string interpolation expressions, File-local types Required members, Auto-default structs, Numeric IntPtr ref fields and scoped ref C# 12 .Net 8 Primary constructors- You can create primary constructors in any class or struct type. Inline arrays - Inline arrays enable you to create an array of fixed size in a struct type. Optional parameters in lambda expressions - You can define default values for parameters on lambda expressions. ref readonly parameters - ref readonly parameters enables more clarity for APIs that might be using ref parameters or in parameters. Alias any type - You can use the using alias directive to alias any type, not just named types. Experimental attribute - Indicate an experimental feature.
  • 4. Keywords • Modifier Keywords: abstract, async, const, event, extern, new, override, partial, readonly, sealed, static, unsafe, virtual, volatile • Access Modifier: public, private, protected, internal • Statement Keyword: if, else, switch, case, do, for, foreach, in, while, break, continue, default, goto, return, yield, throw, try, catch, finally, checked, unchecked, fixed, lock • Method Parameter Keywords: params, ref, out • Namespace Keywords: using, .operator, ::operator, extern, alias • Operator Keywords: as, await, is, new, sizeof, typeof, stackalloc, checked, unchecked • Access Keywords: base, this • Literal Keywords: null, false, true, value, void • Type Keywords: bool, byte, char, class, decimal, double, enum, float, int, long, sbyte, short, string, struct, uint, ulong, ushort • Contextual Keyword: add, var, dynamic, global, set, value
  • 6. Class • class is a group of similar objects. It is a template from which objects are created. It can have fields, methods, constructors, etc. • Object is an instance of a class. All the members of the class can be accessed through the object. Student s1 = new Student();//creating an object of Student • object is an entity that has a state and behavior. Here, state means data, and behavior means functionality. public class Student { public int id; public String name; } class TestStudent{ public static void Main(string[] args) { Student s1 = new Student(); s1.id = 101; s1.name = "KP"; Console.WriteLine(s1.id); Console.WriteLine(s1.name); } }
  • 7. Constructor • A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. • It is used to assign initial values to the data members of the same class. • The constructor of a class must have the same name as the class name in which it resides. • A constructor can not be abstract, final, and Synchronized. • Within a class, you can create only one static constructor. • A constructor doesn’t have any return type, not even void. • A static constructor cannot be a parameterized constructor. • A class can have any number of constructors with different types of arguments. • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor. • Types of Constructor: Default Constructor, Parameterized Constructor, Copy Constructor, Private Constructor, Static Constructor
  • 8. Default Constructor • A constructor with no parameters is called a default constructor. • A default constructor has every instance of the class to be initialized to the same values. • The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class. public class Employee { public Employee() // Default Constructor { Console.WriteLine("Default Constructor Invoked"); } public static void Main(string[] args) { Employee e1 = new Employee(); Employee e2 = new Employee(); } }
  • 9. Parameterized Constructor • A constructor having at least one parameter is called as parameterized constructor. • It can initialize each instance of the class to different values.
  • 10. Copy Constructor • This constructor creates an object by copying variables from another object. • Its main use is to initialize a new instance to the values of an existing instance. • If a Parameterized constructor uses a parameter as the object itself is called a copy constructor. • Generally, c# won’t provide a copy constructor for objects but we can implement ourselves based on our requirements. public User(User user) // Copy Constructor { name = user.name; location = user.location; }
  • 11. Private Constructor • If a constructor is created with a private specifier is known as a Private Constructor. • Private Constructors are used to restrict the creation of an instance for that particular constructor from another class. • If a class contains one or more private constructors and no public constructors, then the other classes are not allowed to create an instance for that particular class except nested classes. • It is the implementation of a singleton class pattern. • Use a private constructor when we have only static members. private Employee() // private Constructor { Console.WriteLine("private Constructor Invoked"); }
  • 12. Static Constructor • Static Constructor has to be invoked only once in the class irrespective of the number of class instances. • A static constructor can only access static members. It cannot contain or access instance members. • It is used to perform a particular action only once throughout the application. • A static constructor is initialized static fields or data of the class and is to be executed only once. • It can’t be called directly. • When it is executing then the user has no control as it will be invoked by CLR. • It does not take access modifiers or any parameters. • It is called automatically to initialize the class before the first instance is created. • only one static constructor is allowed to create. static User() { Console.WriteLine("I am Static Constructor"); }
  • 13. Constructor Chaining • Constructor Chaining: It is an approach to invoke one constructor from another constructor. • To achieve constructor chaining we need to use this keyword after our constructor definition. • Constructor Overloading: C# supports the overloading of constructors, which means we can have constructors with different sets of parameters.
  • 14. Destructor • A destructor works opposite to the constructor, It destructs the objects of classes when they are no longer needed. • It can be defined only once in a class, not in Structures. • An instance variable or an object is eligible for destruction when it is no longer reachable. • Destructor cannot have parameters. Moreover, modifiers can't be applied to destructors. • A Destructor is unique to its class i.e. there cannot be more than one destructor in a class. • A Destructor has no return type and has exactly the same name as the class name (Including the same case). • It is represented by using a tilde (~) operator prefixed to its name. • It cannot be overloaded or inherited. • It is called when the program exits. • Internally, Destructor called the Finalize method on the base class of object by the .NET Framework’s Garbage collector. therefore programmer has no control as to when to invoke the destructor.
  • 15. static keyword • static is a keyword and modifier that belongs to the type not instance. So instance is not required to access the static members. • When a member is declared static, it can be accessed with the name of its class directly. • It applies to fields, methods, constructors, classes, properties, operators, or events. • Memory efficient: Now we don't need to create an instance for accessing the static members, so it saves memory. Moreover, it belongs to the type, so it will not get memory each time when an instance is created. • Shared Memory: The instance of the class will contain a separate copy of all instance fields so the memory consumption will increase automatically, but if we use a static modifier there is only one copy of each field so automatically the memory will be managed efficiently. ⮚ Limitations: • Indexers, destructors, finalizers, and types cannot be static. • static member is not referenced through an instance. • It is not allowed to use this to reference static methods or property accessors. • If a static keyword is used with the class, then the static class always contains static members.
  • 16. static keyword ● Static Class • It is not allowed to create objects of the static class. • All the members of a static class must be static; otherwise the compiler will give an error. • Static classes are sealed, which means one cannot inherit a static class from another class. • A static class cannot contain instance members and constructors. ⮚ Static Variable • When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. • Static variables are accessed with the name of the class, they do not require any object for access. ⮚ Static Method • A static method can access static and non-static fields but cannot access or call non-static variables unless they are explicitly passed as parameters. • static fields are directly accessed by the static method with a class name whereas non-static fields require objects. • Static methods can be overloaded but cannot be overridden. ⮚ Static Constructor • Static Constructor is invoked only once (implicitly) in the class and it has been invoked during the creation of the first reference to a static member in the class. • A static constructor is initialized static fields or data of the class and is to be executed only once.
  • 17. structs • A structure a collection of variables of different data types under a single unit. • Structs can be used to hold small data that is not intended to be modified or inherited after the creation of the structure. • Structs are used for lightweight objects (like Color, rectangles) and defined by the struct keyword. • Unlike class, structs are value types data structures rather than reference types • Struct doesn't support inheritance. But it can implement interfaces. • During struct declaration, the fields cannot be initialized unless they are defined as const or static. • Structures can include fields, properties, member functions, operators, constructors (parameterized & static), events, indexers, constants, operators, nested types, and even other structure types. • Structs cannot include default constructors or destructors but they can contain parameterized constructors. • The default modifier is internal for the struct and its members. • A structure can be instantiated with or without using a new keyword. • Struct members cannot be specified as abstract, sealed, virtual, or protected. • If you declare a variable of struct type without using a new keyword, it does not call any constructor, so all the members remain unassigned. Therefore, you must assign values to each member before accessing them, otherwise, it will give a compile-time error.
  • 18. Class vs structs Class Structs reference types value types contain constructors or destructor contain only parameterized constructor and static constructor Support inheritance Does not support inheritance All the reference types are allocated on heap memory. All the value types are allocated on stack memory. Classes used new keyword for creating instances. Struct can create an instance, with or without a new keyword. The data member of a class can be protected. The data member of struct can’t be protected. Function member of the class can be virtual or abstract. Function member of the struct cannot be virtual or abstract. limitless features and generally used in large programs. limited features and used in small programs
  • 19. enum • Enum is also known as enumeration. • It is used to store a set of named constants such as season, days, month, size etc. The enum constants are also known as enumerators. • Enum can be declared within or outside class and structs. • Enum constants have default values that start from 0 and increment to one by one. But we can change the default value. • Enum has a fixed set of constants • Enum improves type safety • Enum can be traversed • Explicit casting is required to convert from an enum type to its underlying integral type.
  • 20. Partial Classes and Methods • To split the functionality of class, structure, interface or method over multiple files we need to use partial keywords and all files must be available at compile time to form the final type. • The partial modifier can only appear immediately before the keywords class, struct or interface. • All the partial class definitions must be in the same assembly and namespace. • All the parts must have the same accessibility like public or private, etc. • If any part is declared abstract, sealed or base type then the whole class is declared of the same type. • Different parts can have different base types so the final class will inherit all the base types. • The Partial modifier can only appear immediately before the keywords class, struct, or interface. • Nested partial types are allowed. ⮚ Partial Method • Partial methods must use the partial keyword and must return void. • Partial methods can have in or ref but not out parameters. • Partial methods are implicitly private methods, so cannot be virtual. • Partial methods can be static methods. • Partial methods can be generic.
  • 21. Extension Method • Extension methods are additional custom methods which were originally not included with the class. • Extension methods can be added to custom, .NET Framework or third party classes, structs or interfaces. • The first parameter of the extension method must be of the type for which the extension method is applicable, preceded by the this keyword. • Extension methods can be used anywhere in the application by including the namespace of the extension method.
  • 22. Delegates, Events & Anonymous
  • 23. Delegates • Delegate is a reference type variable that holds a reference to a method/function with a specific parameter list and return type. • It is declared by the delegate keyword and acts as a type-safe function pointer. • Provides a good way to encapsulate the methods. • Delegate is the reference type data type that defines the signature. • Delegate type variable can refer to any method with the same signature as the delegate. • Syntax: [access modifier] delegate [return type] [delegate name]([parameters]) • A target method's signature must match with delegate signature. • Delegates can be invoke like a normal function or Invoke() method. • Delegate is used to declare an event and anonymous methods in C#. • Delegates are mainly used in implementing the call-back methods and events. • Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in certain contexts. Sometimes, these features together are known as anonymous functions. • There are three steps involved while working with delegates: 1. Declare a delegate 2. Create an instance and reference a method 3. Invoke a delegate
  • 24. Multicast Delegates • Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast Delegate). It helps the user to point more than one method in a single call. • If a multicast delegate returns a value then it returns the value from the last assigned target method. • Delegates are combined and when you call a delegate then a complete list of methods is called. • All methods are called in First in First Out(FIFO) order. • ‘+’ or ‘+=’ Operator is used to add the methods to delegates. • ‘–’ or ‘-=’ Operator is used to remove the methods from the delegates list. • Limitation • Multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception. • Multicasting of delegate will return the value only from the last method added in the multicast. Although, the other methods will be executed successfully.
  • 25. Advantages and Use of Delegates • Function Pointers: Delegates allow you to treat methods as objects, enabling you to pass methods as parameters to other methods, store them in data structures, or return them from methods. This is similar to function pointers in languages like C and C++. • Event Handling: It is commonly used in event handling in C# to implement the observer pattern. Events in C# are based on delegates, and they allow objects to subscribe to and receive notifications when certain actions or events occur. • Decoupling: Delegates help in decoupling the calling code from the implementation of the method being called. This promotes separation of concerns and makes the code more modular and maintainable. • Dynamic Behavior: Delegates provide a way to achieve dynamic behavior in your code by allowing you to change the method being called at runtime. This can be useful in scenarios where you need to switch between different implementations of a method based on certain conditions. • Callback Functions: Delegates are often used to implement callback functions where a method can call back to a method defined in another class or part of the codebase. • Multi-cast Delegates: Delegates in C# support multi-cast functionality, which means you can combine multiple methods into a single delegate instance. When you invoke a multi-cast delegate, all the methods it points to are called in the order they were added. • Anonymous Methods and Lambda Expressions: Delegates work well with anonymous methods and lambda expressions, allowing for more concise and readable code, especially for event handling and asynchronous programming.
  • 26. Func & Action Delegate • Func and Action is a generic delegate included in the System namespace. • Func and Action is built-in delegate type. • Func and Action delegate type can be used with an anonymous method or lambda expression. Func • Func can have zero to 16 input parameters of different types and one out parameter. The last parameter is considered as an out parameter. • Func delegate type must return a value. • Func delegate does not allow ref and out parameters. Action • Action delegate is same as func delegate except that it does not return anything. Return type must be void. • Action delegate can have 0 to 16 input parameters of different types. Advantages of Func and Action • Easy and quick to define delegates. • Makes code short. • Compatible type throughout the application.
  • 27. Predicate Delegate • Predicate is the delegate like Func and Action delegates. • It represents a method containing a set of criteria and checks whether the passed parameter meets those criteria. • A predicate delegate methods must take one input parameter and return a boolean - true or false. • Anonymous method and Lambda expression can be assigned to the predicate delegate.
  • 28. Anonymous Types • Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. • The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler. • an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc. • var student = new { Id = 1, FirstName = "James", LastName = "Bond" }; • The properties of anonymous types are read-only and cannot be initialized with a null, anonymous function, or a pointer type. • An anonymous type will always be local to the method where it is defined. It cannot be returned from the method. • an anonymous type can be passed to the method as object type parameter, but it is not recommended. • If you need to pass it to another method, then use struct or class instead of an anonymous type. • Mostly, anonymous types are created using the Select clause of a LINQ queries to return a subset of the properties from each object in the collection. • Anonymous types contain one or more public read-only properties. • To create an anonymous type using the new operator with an object initializer syntax. • The implicitly typed variable- var is used to hold the reference of anonymous types. • The properties can be accessed using dot (.) notation, same as object properties. However, you cannot change the values of properties as they are read-only. • This can be nested.
  • 29. Anonymous Method • An anonymous method is a method without a name. • It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods. • An Anonymous method is defined using the delegate keyword and must be assign this method to a variable of the delegate type. • This method is also known as inline delegate. • Using this method you can create a delegate object without writing separate methods. • This method can access variable present in the outer method like as Outer variables. • This method can be pass to another method which accepts delegate as a parameter. • The anonymous-method-block means the scope of the parameters in the anonymous method. • You can also use an anonymous method as an event handler. • Limitations • An anonymous method does not contain jump statements like goto, break, or continue. • An anonymous method does not access unsafe code. • An anonymous method does not access in, ref, and out parameter of the outer scope. • You can not use an anonymous method to the left side of the is operator.
  • 30. Events • An event is a wrapper around a delegate. It depends on the delegate. • Use "event" keyword with delegate type variable to declare an event. • Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events. • The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method. • Name the method which raises an event prefixed with "On" with the event name. • The signature of the handler method must match the delegate signature. • Register with an event using the += operator. Unsubscribe it using the -= operator. Cannot use the = operator. • Pass event data using EventHandler<TEventArgs>. • Derive EventArgs base class to create custom event data class. • Events can be declared static, virtual, sealed, and abstract. • An Interface can include the event as a member. • Event handlers are invoked synchronously if there are multiple subscribers.
  • 31. Delegate vs Events Delegate Events A delegate is declared using the delegate keyword. An event is declared using the event keyword. Delegate is a function pointer. It holds the reference of one or more methods at runtime. The event is a notification mechanism that depends on delegates Delegate is independent and not dependent on events. An event is dependent on a delegate and cannot be created without delegates. Event is a wrapper around delegate instance to prevent users of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list. Delegate includes Combine() and Remove() methods to add methods to the invocation list. EventInfo class inspect events and to hook up event handlers that include methods AddEventHandler() and RemoveEventHandler() methods to add and remove methods to invocation list, respectively. A delegate can be passed as a method parameter. An event is raised but cannot be passed as a method parameter. = operator is used to assigning a single method, and += operator is used to assign multiple methods to a delegate. = operator cannot be used with events, and only += and -= operator can be used with an event that adds or remove event handler. These methods internally call AddEventHandler and RemoveEventHandler methods.
  • 33. Generics • Generic means the general form, means not specific to a particular data type. • Generic can be classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type. • Generics are type-safe. You get compile-time errors if you try to use a different data type than the one specified in the definition. • Generic has a performance advantage because it removes the possibilities of boxing and unboxing. • A generic class increases the reusability. The more type parameters mean more reusable it becomes. However, too much generalization makes code difficult to understand and maintain. • A generic class can be a base class to other generic or non-generic classes or abstract classes. • A generic class can be derived from other generic or non-generic interfaces, classes, or abstract classes. • A generic class can include generic fields. However, it cannot be initialized.
  • 34. Generics Constraints • C# allows to use constraints to restrict client code to specify certain types while instantiating generic types. • It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints. • can specify one or more constraints on the generic type using the where clause after the generic type name. Constrains The type argument must be class any class, interface, delegate, or array type. class? a nullable or non-nullable class, interface, delegate, or array type. struct non-nullable value types such as primitive data types int, char, bool, float, etc. new() a reference type which has a public parameterless constructor. It cannot be combined with struct and unmanaged constraints. notnull non-nullable reference types or value types. If not, then the compiler generates a warning instead of an error. unmanaged non-nullable unmanged types. base class name or derive from the specified base class. The Object, Array, ValueType classes are disallowed as a base class constraint. The Enum, Delegate, MulticastDelegate are disallowed as base class constraint before C# 7.3.
  • 36. Garbage Collection • Garbage collector is responsible for managing memory and automatically freeing up memory that is no longer being used by the application. • It works by periodically scanning the application’s memory to determine which objects are still being used and which are no longer needed. • Objects that are no longer being used are marked for garbage collection, and their memory is freed up automatically by the garbage collector.
  • 37. Feature of Garbage Collection • Automatic memory management: With the garbage collector, developers don’t need to worry about manually allocating or freeing up memory. The garbage collector takes care of memory management automatically, which can help reduce the risk of memory leaks and other issues. • Low impact on application performance: The garbage collector runs in the background and typically has a low impact on application performance. However, in some cases, garbage collection can cause brief pauses or slowdowns in the application, particularly when large amounts of memory need to be freed up at once. • Generation-based collection: The garbage collector in C# uses a generation-based approach to memory management. Objects are initially allocated in a “young” generation and are moved to an “old” generation if they survive multiple garbage collection cycles. This approach helps reduce the amount of time required for garbage collection, as most objects are collected in the young generation. • Finalization: The garbage collector also provides support for finalization, which is a process that allows objects to perform cleanup tasks before they are destroyed. Objects with finalizers are moved to a separate finalization queue, which is processed by the garbage collector after all other objects have been collected.
  • 38. Phases in Garbage Collection 1. Marking Phase: A list of all the live objects is created during the marking phase. This is done by following the references from all the root objects. All of the objects that are not on the list of live objects are potentially deleted from the heap memory. 2. Relocating Phase: The references of all the objects that were on the list of all the live objects are updated in the relocating phase so that they point to the new location where the objects will be relocated to in the compacting phase. 3. Compacting Phase: The heap gets compacted in the compacting phase as the space occupied by the dead objects is released and the live objects remaining are moved. All the live objects that remain after the garbage collection are moved towards the older end of the heap memory in their original order.
  • 39. Generations in Garbage Collection • The heap memory is organized into 3 generations so that various objects with different lifetimes can be handled appropriately during garbage collection. The memory to each Generation will be given by the (CLR) depending on the project size. Internally, Optimization Engine will call the Collection Method to select which objects will go into which Generation. • Generation 0 : All the short-lived objects such as temporary variables are contained in the generation 0 of the heap memory. All the newly allocated objects are also generation 0 objects implicitly unless they are large objects. In general, the frequency of garbage collection is the highest in generation 0. • Generation 1 : If space occupied by some generation 0 objects that are not released in a garbage collection run, then these objects get moved to generation 1. The objects in this generation are a sort of buffer between the short-lived objects in generation 0 and the long- lived objects in generation 2. • Generation 2 : If space occupied by some generation 1 objects that are not released in the next garbage collection run, then these objects get moved to generation 2. The objects in generation 2 are long lived such as static objects as they remain in the heap memory for the whole process duration. • Memory Allocation : Generation 2 > Generation 1 > Generation 0
  • 40. Methods in Garbage Collection • GC.GetGeneration() : This method returns the generation number of the target object. It requires a single parameter i.e. the target object for which the generation number is required. • GC.GetTotalMemory() : This method returns the number of bytes that are allocated in the system. It requires a single boolean parameter where true means that the method waits for the occurrence of garbage collection before returning and false means the opposite. • GC.Collect() : Garbage collection can be forced in the system using the GC.Collect() method. This method requires a single parameter i.e. number of the oldest generation for which garbage collection occurs. • GC.SuppressFinalize() : This system method is designed to prevent calling the finalizer on the specified object by CLR.
  • 41. Benefit of Garbage Collection • Garbage Collection succeeds in allocating objects efficiently on the heap memory using the generations of garbage collection. • Manual freeing of memory is not needed as garbage collection automatically releases the memory space after it is no longer required. • Garbage collection handles memory allocation safely so that no object uses the contents of another object mistakenly. • The constructors of newly created objects do not have to initialize all the data fields as garbage collection clears the memory of objects that were previously released.
  • 42. Concurrent Garbage Collection • Concurrent garbage collection is performed on a dedicated thread. • This enables threads to run concurrently with a dedicated thread that performs the garbage collection for most of the duration of the collection. • This option affects only garbage collections in generation 2; generations 0 and 1 are always non- concurrent because they finish fast.
  • 44. throw vs throw ex vs throw new Exception()  Stack Trace Preservation • throw: Preserves the original stack trace, providing complete information about where the exception originated. • throw ex: Resets the stack trace, which can make it harder to debug the root cause of the exception. • throw new Exception("An error occurred", ex): Provides additional context with a new exception message while preserving the original exception as an inner exception.  Use Cases • throw: Use this when you want to maintain the original exception context and stack trace, which is almost always the preferred approach. • throw ex: Use this sparingly, and only when you need to add additional information to the exception before rethrowing it. • throw new Exception("An error occurred", ex): Use this when you want to add more context to the exception while retaining the original exception details.
  • 46. Main Thread  Multithreading refers to the capability to create and manage multiple threads within a single process. A thread is the smallest unit of execution within a process, and multiple threads can run concurrently, sharing the same resources of the parent process but executing different code paths. • Ideal for CPU-bound tasks that can be parallelized, such as image processing, video encoding, or mathematical computations, as well as scenarios requiring responsive user interfaces.  Main Thread: When a C# program starts up, one thread begins running immediately. This is usually called the main thread of our program. • It is the first thread under which all child thread created. • Often, it must be the last thread to finish execution because it performs various shutdown actions. • The main thread works just like other thread but it starts automatically, you need not to require any Start() method to start the execution of the main thread. • CurrentThread property : to access the main thread or inside the main thread to get the reference of the main thread. Thread.CurrentThread • Deadlock using Main Thread : a deadlock can be created by just using Main thread. Thread.CurrentThread.Join(); • The statement “Thread.currentThread().join()”, will tell the Main thread to wait for this thread(i.e. wait for itself) to die. Thus the Main thread waits for itself to die, which is nothing but a deadlock.
  • 47. Thread Life Cycle • Thread Life Cycle states: Unstarted, Runnable (Ready to run), Running, Not Runnable (Sleep(), Wait(), Due to I/O request, Suspend()), Dead (Terminated)
  • 48. Thread Class • A multi-threading system is built upon the Thread class, which encapsulates the execution of threads. • This class contains several methods and properties which helps in managing and creating threads and this class is defined under System.Threading namespace. • Thread class is used to create threads. • Using this can be created foreground and background thread. • Thread class allows to set the priority of a thread. • It also provides the current state of a thread. • It provides the reference of the current executing thread. • It is a sealed class, so it cannot be inherited. • Constructor: Thread(ParameterizedThreadStart), Thread(ParameterizedThreadStart, Int32), Thread(ThreadStart), Thread(ThreadStart, Int32) • Properties: CurrentContext, CurrentCulture, CurrentThread, IsAlive, IsBackground, IsThreadPoolThread, Name, Priority, ThreadState • Method: Abort(), Equals(Object), Finalize(), GetType(), Interrupt(), Join(), ResetAbort(), Resume(), Sleep(), SpinWait(Int32), Start(), Suspend(), ToString(), Yield()
  • 49. Thread Types  Foreground Threads: They prevent the application from terminating until all foreground threads have completed their tasks. • A foreground thread can be created by calling the Thread.Start() method. • When an application starts, it automatically creates a foreground thread, i.e. main thread of the application. • All threads generated by creating and starting a new Thread object are by default foreground threads. However, you can change the type of a thread by setting the IsBackground property of the thread. • Foreground threads are useful when need to perform a task that is critical to the operation of the application and must be completed before the application can terminate. • Ex.- a foreground thread might be used to update the user interface or to perform important calculations. • Foreground thread does not care whether the main thread is alive or not, it completes only when it finishes its assigned work.  Background Threads: They do not prevent the application from terminating, even if they are still running. • A background thread can be created by calling the Thread.Start() method and then setting the IsBackground property of the thread to true before starting it. • Background threads are useful when need to perform a task that is not critical to the operation of the application and can be terminated if the application needs to shut down. • Ex.- a background thread might be used to download a large file or to perform periodic updates to a database. • A thread which leaves its process when the Main method leaves its process, these types of the thread are known as the background threads. • All threads that enter the managed execution environment from unmanaged code are marked as background threads.
  • 50. Thread Join  Thread.Join() : The Join method of the Thread class waits for the thread to complete its execution before continuing with the execution of the calling thread. • This method blocks the calling thread until the target thread has completed its execution. • Join() Overload : Join(), Join(Int32) , Join(TimeSpan)  Task.WaitAll(): The WaitAll method of the Task class waits for all the specified tasks to complete before continuing with the execution of the calling thread. • This method blocks the calling thread until all the specified tasks have completed their execution.
  • 52. Asynchronous Programming • Asynchronous Programming: Using asynchronous programming indicates that a method can execute without waiting for another method to complete. Using async and await, we can run the methods above parallelly. • An async keyword is a method that performs asynchronous tasks such as fetching data from a database, reading a file, etc, they can be marked as “async”. • await keyword making “await” to a statement means suspending the execution of the async method it is residing in until the asynchronous task completes. • After suspension, the control goes back to the caller method. Once the task completes, the control comes back to the states where await is mentioned and executes the remaining statements in the enclosing method. • await can only be used inside an async method. • If a method which uses async modifier does not contain await expression, executes synchronously. • the async method cannot use ref or out parameters. • Return type: Task, Task<TResult>, Void (for event handlers), Tasks.ValueTask<TResult> • Use Case: I/O-bound operations (like reading from a file, fetching data from the web, or querying a database), network communication, file I/O, and database access, where non-blocking execution and scalability are essential.
  • 53. Multithreading vs Asynchronous vs Parallel Programming  Multithreading focuses on allowing multiple threads to operate concurrently, often within a single process, to maximize resource usage and maintain responsiveness. So, Multithreading is a process that contains multiple threads within a single process. Here, each thread performs different activities. • Multithreading involves the concurrent execution of multiple threads within a process. • Effective in scenarios where parallelism can significantly enhance performance. • Ideal for CPU-bound tasks that can be parallelized, such as image processing, video encoding, or mathematical computations, as well as scenarios requiring responsive user interfaces.  Asynchronous Programming focuses on non-blocking operations, especially for I/O-bound tasks, ensuring responsiveness and scalability without waiting for each to complete. • Improved efficiency by avoiding idle time during I/O operations. • Well-suited for I/O-bound operations, such as reading from or writing to databases or making API calls. network communication, file I/O, and database access, where non-blocking execution and scalability are essential.  Parallel Programming focuses on splitting tasks to run simultaneously on multiple processors or cores to reduce total computation time for CPU-bound operations. • In this case, it will use multiple processors to execute different parts of a task; each processor has multiple threads that can execute the application code.
  • 54. Thanks for the Attention... Happy Coding...