0% found this document useful (0 votes)
6 views

1. CSharp

The document provides an overview of access modifiers in C#, including public, private, protected, internal, protected internal, and private protected, explaining their accessibility rules. It also covers various types of classes such as abstract, partial, sealed, and static, along with different types of methods including virtual, abstract, and extension methods. Additionally, it discusses constructors and exception handling, highlighting built-in exceptions and their purposes, as well as the concept of collections in C#.

Uploaded by

tarangkarkar79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

1. CSharp

The document provides an overview of access modifiers in C#, including public, private, protected, internal, protected internal, and private protected, explaining their accessibility rules. It also covers various types of classes such as abstract, partial, sealed, and static, along with different types of methods including virtual, abstract, and extension methods. Additionally, it discusses constructors and exception handling, highlighting built-in exceptions and their purposes, as well as the concept of collections in C#.

Uploaded by

tarangkarkar79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Access Modifiers

19 April 2023 16:45

Public
The public keyword is an access modifier for types and type members. Public
access is the most permissive access level.

There are no restrictions on accessing public members.

Accessibility
• Can be accessed by objects of the class
• Can be accessed by derived classes

Private
Private access is the least permissive access level.

Private members are accessible only within the body of the class or the struct
in which they are declared.

Accessibility
• Cannot be accessed by object of another class
• Cannot be accessed by derived classes

Protected
A protected member is accessible from within the class in which it is declared,
and from within any class derived from the class that declared this member.

A protected member of a base class is accessible in a derived class only if the


access takes place through the derived class type.

Accessibility
• Cannot be accessed by object of another class
• By derived classes

Note: Elements defined inside namespace should not be private,


protected, protected internal or private protected.

Internal
The internal keyword is an access modifier for types and type members. We
can declare a class as internal or its member as internal. Internal members are
accessible only within files in the same assembly (.dll).

In other words, access is limited exclusively to classes defined within the


current project assembly.

Accessibility

In same assembly (public)


• Can be accessed by objects of the class
• Can be accessed by derived classes
In other assembly (internal)
• Cannot be accessed by object
• Cannot be accessed by derived classes

Protected Internal

The protected internal accessibility means protected OR internal, not protected


AND internal.

In other words, a protected internal member is accessible from any class in the
same assembly, including derived classes.

The protected internal access modifier seems to be a confusing but is a union


of protected and internal in terms of providing access but not restricting. It
allows:
• Inherited types, even though they belong to a different assembly, have
access to the protected internal members.
• Types that reside in the same assembly, even if they are not derived from
the type, also have access to the protected internal members.

Default access
A default access level is used if no access modifier is specified in a member
declaration. The following list defines the default access modifier for certain C#
types:

enum: The default and only access modifier supported is public.


class: The default access for a class is internal. It may be explicitly defined
using any of the access modifiers.
interface: The default and only access modifier supported is public.
struct: The default access is private with public and internal supported as well.

The default access may suffice for a given situation, but you should specify the
access modifier you want to use to ensure proper application behaviour.

Note: Interface and enumeration members are always public and no access
modifiers are allowed.

Private Protected
Access is limited to the containing class or types derived from the containing
class within the current assembly.

From <https://www.c-sharpcorner.com/uploadfile/puranindia/what-are-access-modifiers-in-C-Sharp/>
Class
19 April 2023 16:01

User defined data type which has state and behaviour.

Access modifiers of class


Public
Private
Protected
Internal
Protected Internal

Types of Class
Abstract
An abstract class is a class that provides a common definition to the subclasses,
and this is the type of class whose object is not created.
Some key points of Abstract classes are:
• Abstract classes are declared using the abstract keyword.
• We cannot create an object of an abstract class.
• It must be inherited in a subclass if you want to use it.
• An Abstract class contains both abstract and non-abstract methods.
• The methods inside the abstract class can either have an or no
implementation.
• We can inherit two abstract classes; in this case, implementation of the
base class method is optional.
• An Abstract class has only one subclass.
• Methods inside the abstract class cannot be private.
• If there is at least one method abstract in a class, then the class must be
abstract.

Partial
It is a type of class that allows dividing their properties, methods, and events
into multiple source files, and at compile time, these files are combined into a
single class.
The following are some key points:
• All the parts of the partial class must be prefixed with the partial keyword.
• If you seal a specific part of a partial class, the entire class is sealed, the
same as for an abstract class.
• Inheritance cannot be applied to partial classes.
• The classes written in two class files are combined at run time.
Sealed
A Sealed class is a class that cannot be inherited and used to restrict the
properties.
The following are some key points:
• A Sealed class is created using the sealed keyword.
• Access modifiers are not applied to a sealed class.
• To access the sealed members, we must create an object of the class.

Static
It is the type of class that cannot be instantiated. In other words, we cannot
create an object of that class using the new keyword, such that class members
can be called directly using their name.
The following are some key points:
• It was created using the static keyword.
• Only static members are allowed; in other words, everything inside the
class must be static.
• We cannot create an object of the static class.
• A Static class cannot be inherited.
• It allows only a static constructor to be declared.
• The static class methods can be called using the class name without
creating the instance.
Methods
19 April 2023 16:31

Pure Virtual Method

Pure virtual method is the term that programmers use in C++. There is a term
"abstract" in place of "pure virtual method" in C#.

Virtual Method

Virtual method makes some default functionality. In other words, virtual


methods are being implemented in the base class and can be overridden in the
derived class.

Abstract Method

Abstract Method is the method with no implementation and is implicitly


virtual. You can make abstract method only in Abstract class.
Default modifier of abstract method inside abstract class is public.

Partial Method

A partial method has its signature defined in one part of a partial type, and its
implementation defined in another part of the type.

Extension Method

Extension methods are a special kind of static method, but they are called as if
they were instance methods on the extended type.

Extension methods are used to add some functionality to given type.

Note:
1. For making Extension methods, you need to have a static class with static
method.
2. Do not make Extension method for one or two lines of code, write
Extension method for logic.
3. An extension method must be defined in a top-level static class.
4. An extension method with the same name and signature as an instance
method will not be called.
5. Extension methods cannot be used to override existing methods.
6. The concept of extension methods cannot be applied to fields, properties,
or events.

Benefits of extension methods:


• Extension methods allow existing classes to be extended without relying
on inheritance or changing the class's source code.
• If the class is sealed, there is no concept of extending its functionality. For
this, a new concept is introduced.

Instance Method

An instance method operates on a given instance of a class, and that instance


can be accessed as this.

Static Method

This belongs to the type, it does not belong to instance of the type. You can
access static methods by class name.

You can put static method in static or non- static classes.

The only difference is that static methods in a non-static class cannot be


extension methods.

Static often improves performance.


From <https://www.c-sharpcorner.com/article/type-of-methods-in-c-sharp/>
Constructor
19 April 2023 17:31

Constructor is a special type of method which is invoked at the time of object


creation.
Constructor has two works:
1. Create the instance
2. Initialize the object properties with values

Main use of constructor is to initialize the private fields of the class while
creating an instance of the class.

Some of the key points regarding constructor are,


• A class can have any number of constructors.
• A constructor doesn't have any return type, not even void.
• A static constructor can not be a parametrized constructor.
• Within a class, you can create one static constructor only.

Default Constructor
A constructor without any parameters is called a default constructor; in other
words, this type of constructor does not take parameters. The drawback of a
default constructor is that every instance of the class will be initialized to the
same values and it is not possible to initialize each instance of the class with
different values. The default constructor initializes:
1. All numeric fields in the class to zero.
2. All string and object fields to null.

Parameterized Constructor
A constructor with at least one parameter is called a parameterized constructor.
The advantage of a parameterized constructor is that you can initialize each
instance of the class with a different value.

Copy Constructor
If we want to create multiple instances with the same values then we need to
use the copy constructor.
The constructor which creates an object by copying variables from another
object is called a copy constructor. The purpose of a copy constructor is to
initialize a new instance to the values of an existing instance.

Static Constructor
When a constructor is created using a static keyword, it will be invoked only once
for all of the instances of the class and it is invoked during the creation of the
first instance of the class or the first reference to a static member in the class. A
static constructor is used to initialize static fields of the class and to write the
code that needs to be executed only once.
Some key points of a static constructor are:
1. A static constructor does not take access modifiers or have parameters.
2. A static constructor is called automatically to initialize the class before the
first instance is created or any static members are referenced.
3. A static constructor cannot be called directly.
4. The user has no control over when the static constructor is executed in the
program.
5. A typical use of static constructors is when the class is using a log file and
the constructor is used to write entries to this file.

Private Constructor
When a constructor is created with a private specifier, it is not possible for other
classes to derive from this class, neither is it possible to create an instance of
this class from outside. They are usually used in classes that contain static
members only. Some key points of a private constructor are:
1. One use of a private constructor is when we have only static members.
2. It provides an implementation of a singleton class pattern.
3. Once we provide a constructor that is either private or public or any, the
compiler will not add the parameter-less public constructor to the class.

From <https://www.c-sharpcorner.com/UploadFile/0c1bb2/constructors-and-its-types-in-C-Sharp/>
Partial Class
21 April 2023 10:51

Physically Different but Logically same entity

Rules for Partial Classes:


• 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.
• The Partial modifier can only appear immediately before the keywords class, struct,
or interface.
• Nested partial types are allowed.

Rules for Partial Methods:


• Partial methods must use the partial keyword.
• Partial method can return any type.
• Partial methods can have in or ref but not out parameters.
• Partial methods are implicitly private methods, so cannot be virtual. (Now it can be virtual)
• Partial methods can be static methods.
• Partial methods can be generic.
Static
21 April 2023 12:18

C# classes, variables, methods, properties, operators, events, and constructors


can be defined as static using the static modifier keyword.

Rules for Static Class


1. Static classes cannot be instantiated.
2. All the members of a static class must be static; otherwise the compiler
will give an error.
3. A static class can contain static variables, static methods, static properties,
static operators, static events, and static constructors.
4. A static class cannot contain instance members and constructors.
5. Indexers and destructors cannot be static.
6. var cannot be used to define static members. You must specify a type of
member explicitly after the static keyword.
7. Static classes are sealed class and therefore, cannot be inherited.
8. A static class cannot inherit from other classes.
9. Static class members can be accessed using ClassName.MemberName.
10. A static class remains in memory for the lifetime of the application domain
in which your program resides.

Rules for Static Methods


1. Static methods can be defined using the static keyword before a return
type and after an access modifier.
2. Static methods can be overloaded but cannot be overridden.
3. Static methods can contain local static variables.
4. Static methods cannot access or call non-static variables unless they are
explicitly passed as parameters.

Static Constructors
A non-static class can contain a parameterless static constructor. It can be
defined with the static keyword and without access modifiers like public,
private, and protected.

The static constructor is called only once whenever the static method is used
or creating an instance for the first time.

Calling the static method second time onwards won't call a static constructor.

Static constructor of Interface will only call if we invoke implemented


method of an interface.
Rules for Static Constructors
1. The static constructor is defined using the static keyword and without
using access modifiers public, private, or protected.
2. A non-static class can contain one parameterless static constructor.
Parameterized static constructors are not allowed.
3. Static constructor will be executed only once in the lifetime. So, you
cannot determine when it will get called in an application if a class is being
used at multiple places.
4. A static constructor can only access static members. It cannot contain or
access instance members.

Static members are stored in a special area in the memory called High-
Frequency Heap. Static members of non-static classes are shared across all the
instances of the class. So, the changes done by one instance will be reflected in
all the other instances.
From <https://www.tutorialsteacher.com/csharp/csharp-static>
Built-In Exception
25 April 2023 10:13

Exception:
an exception is an event that disrupts the normal flow of the program. It is an
object which is
thrown at runtime.

Exception Handling:
Exception Handling is a mechanism to handle runtime errors.

Advantage of Exception Handling:


The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions.

ArgumentException Raised when a non-null argument that is passed to a method is invalid.


ArgumentNullException Raised when null argument is passed to a method.
ArgumentOutOfRangeException Raised when the value of an argument is outside the range of valid values.
DivideByZeroException Raised when an integer value is divide by zero.
FileNotFoundException Raised when a physical file does not exist at the specified location.
FormatException Raised when a value is not in an appropriate format to be converted from a
string by a conversion method such as Parse.
IndexOutOfRangeException Raised when an array index is outside the lower or upper bounds of an
array or collection.
InvalidOperationException Raised when a method call is invalid in an object's current state.
KeyNotFoundException Raised when the specified key for accessing a member in a collection is not
exists.
NotSupportedException Raised when a method or operation is not supported.
NullReferenceException Raised when program access members of null object.
OverflowException Raised when an arithmetic, casting, or conversion operation results in an
overflow.
OutOfMemoryException Raised when a program does not get enough memory to execute the code.
StackOverflowException Raised when a stack in memory overflows.
TimeoutException The time interval allotted to an operation has expired.
Collections
04 May 2023 11:19

• Collections are group of records that can be treated as


single logical entity.
• All the collection classes(generic and non-generic)
implements IEnumerable interface.

ArrayList:
Methods:
1. ArrayList(): The method is used to initialize a new instance of the ArrayList
class that is empty and has the default initial capacity.

2. ArrayList(ICollection c): The method is used to initialize a new instance of


the ArrayList class that contains elements copied from the specified
collection and that have the same initial capacity as the number of
elements copied. The parameter c specifies the Collection whose
elements are copied to the new list.

3. ArrayList(int capacity): The method is used to initialize a new instance of


the ArrayList class that is empty and has the specified initial capacity. The
parameter capacity specifies the number of elements that the new list can
initially store.

Insert()
InsertRange()
Remove()
RemoveAt()
RemoveRange()
Clear()
Contains()
Clone(): This method is used to create and return a shallow copy of the
ArrayList.
Sort()

Hashtable:
Contains()
ContainsKey()
ContainsValue()
Remove()
Clear()
CopyTo(array, index)

Stack:
Push()
Pop()
Clear()
Peek()
Contains()
Clone()

Queue:
Enqueue()
Dequeue()
Peek()
Clear()
Contains()

Count: It gets the number of elements contained in the Queue.

IsSynchronized: It gets a value indicating whether access to the Queue is


synchronized (thread-safe). It returns true if access to the queue is
synchronized (thread-safe); otherwise, false. The default is false.

SyncRoot: It gets an object that can be used to synchronize access to the


Queue. It returns an object that can be used to synchronize access to the
queue.

SortedList:

Disadvantages of using Non-Generic Collection Classes in C#:

The Non-Generic Collection Classes such as ArrayList, Stack, Queue, Hashtable,


SortedList, etc operate on the object data type. As they operate on object data
type hence they are loosely typed. Loosely typed means you can store any type
of value in the collection. Because of this loosely typed nature, we may get
runtime errors.

The Collection Classes belong to System.Collections namespace operates on


the object data type. The object data type in C# is a reference data type. So the
value that we store in the collection is converted to reference type. So in our
example, the values 100 and 200 are boxed and converted into the reference
type. In our example, we just stored two values. Consider a scenario where we
need to store 1000 integer values. Then all 1000 integers need to be boxed,
meaning they are converted into reference types and then stored in the
collection.
Generic Collection
04 May 2023 16:32

Used to overcome this two problems:


1. Array is fixed sized.
2. Non-generic collections are type-unsafe.
3. Boxing happens every time when we store data in Non-
generic collection.

List<T>

HashSet<T>
UnionWith(): union of two hashsets.
IntersectWith(): intersection of two hashsets
ExpectWith(): elements from the first collection that are not prsent in second
one.
SymmetricExpectWith(): elements that are not common in both collection

SortedSet<T>
Min
Max
Count
Comparer: Returns the comparer that is used to order the values in the
Generic SortedSet.

Stack<T>

Queue<T>

Dictionary<TKey, TValue>

SortedDictionary<TKey, TValue>

SortedList<TKey, TValue>
• SortedList uses less memory than SortedDictionary
• SortedDictionary has faster insertion and removal.
• SortedList are created using Array(O(n)) while SortedDictionary are
created using BinaryTree(O(log n)).
• If data is already sorted than SortedList works faster than
SortedDictionary.
• SortedList is better if we want to access elements frequently while
SortedDictionary is better if we want to insert and remove elements
frequently.

LinkedList<T>
Each node in linked list is a type of LinkedListNode<T>
AddAfter()
AddBefore()
AddLast()
AddFirst()
Remove(LinkedListNode<T> node): removes specified node from the list
Remove(value): removes first occurrence of specified value from the list
Concurrent Collection
05 May 2023 15:19

• Multithreading: Multiple instances are trying to


add/update/delete/retrieve resource simultaneously.

• C# 1.0 introduced System.Collections which contains non-


generic collections (not type safe)

• C# 2.0 introduced System.Collections.Generic which


contains generic collections (type safe but not thread
safe)

• C# 4.0 introduced System.Collections.Concurrent which


contains concurrent collections (type safe and thread
safe)

Concurrent Dictionary
AddOrUpdate()
GetOrAdd()
TryGetValue()

Concurrent Stack
Concurrent Queue
Concurrent List
ConcurrentBag: allows to store duplicate objects. Similar to
List<T>.
Add()
TryTake()
TryPeek()
CopyTo(): copy to the existing array
ToArray(): copy by creating new array

BlockingCollection: set max capacity, add/update values by multiple


threads, block insertion and removal while capacity is full/null, implement
producer-consumer pattern.
Difference between Sorted List, Dictionary and Hashtable
26 April 2023 13:08

In C#, a sorted list, dictionary, and hashtable are all collections of


data. However, they differ in their implementation, functionality, and
performance. Here's a brief overview of each.

Sorted List:
A sorted list is a collection that contains key-value pairs, where keys
are unique and are sorted in ascending order. It is implemented as
an array-based list, where elements are stored in a contiguous block
of memory. This allows for efficient indexing and searching, but
inserts and removals can be slower as the list needs to be rearranged
to maintain the order.

Dictionary:
A dictionary is also a collection of key-value pairs, but unlike a sorted
list, the keys are not sorted. It uses hashing to map keys to values,
which provides constant time lookups, inserts, and removals.
However, the order of elements is not guaranteed, and iterating over
the elements can be slower than in a sorted list.

Hashtable:
A hashtable is similar to a dictionary in that it uses hashing to map
keys to values, but it is an older implementation that is not as
efficient as the dictionary. It can have collisions (i.e., two different
keys may map to the same index in the hashtable), which can slow
down lookups and inserts. It also does not provide type safety and is
not recommended for use in newer code.

In summary, if you need to maintain the order of elements based on


keys, a sorted list is the best option. If you need constant time
lookups, inserts, and removals, but don't care about the order of
elements, a dictionary is the way to go. And if you're working with
legacy code, or need to interoperate with other systems that use
hashtables, you may need to use a hashtable.
Differences
08 May 2023 15:55

Class vs Struct
Class Structure
Classes are of reference types. Structs are of value types.
All the reference types are allocated on All the value types are allocated on stack
heap memory. memory.
Allocation of large reference type is Allocation and de-allocation is cheaper in value
cheaper than allocation of large value type as compare to reference type.
type.
Class has limitless features. Struct has limited features.
Class is generally used in large Struct are used in small programs.
programs.
Classes can contain constructor or Structure does not contain parameter less
destructor. constructor or destructor, but can contain
Parameterized constructor or static constructor.
(NOW FROM C# 10 STRUCT CAN CONTAIN
PARAMETERLESS CONSTRUCTOR)
Classes used new keyword for creating Struct can create an instance, with or without
instances. new keyword.
A Class can inherit from another class. A Struct is not allowed to inherit from another
struct or class.
The data member of a class can be The data member of struct can’t be protected.
protected.
Function member of the class can be Function member of the struct cannot be virtual
virtual or abstract. or abstract.
Two variable of class can contain the Each variable in struct contains its own copy of
reference of the same object and any data(except in ref and out parameter variable)
operation on one variable can affect and any operation on one variable can not
another variable. effect another variable.
Class type in generic constraint is used Struct type in generic constraint is used to
to restrict type of class for reference- restrict type of class for value type only.
type only.

Enum vs Struct
1. The enum keyword is used to declare an enumeration
2. Enum represents a set of Named constants (we cannot change the values associated
with enums since Enums are treated as Constants).
3. Enum will be having an underlying type as Integral Type. (Except Char)
4. The default underlying type of the enumeration elements is int
5. By default, the first enumerator has the value 0, and the value of each successive
enumerator is increased by 1.
6. Enums are value type
7. Enums make your code much more readable and understandable.
8. We can declare Enum either in a class or outside of a class as well
9. Enum cannot inherit from other Enum.

Struct is just like class but is light weight and faster.


1. Within a struct declaration, fields cannot be initialized unless they are declared as
const or static.
2. All structs inherit directly from System.ValueType, which inherits from System.Object.
3. We can directly intialize the const or static fileds in the Struct.
4. we can implement interfaces in structs but we cannot inherit a struct from other
struct or class.
5. Because copies of structs are created and destroyed automatically by the JIT
compiler, a default constructor and destructor are unnecessary.
6. Structs are by default sealed.
7. Value types are faster than reference types.
8. Most of the primitive types in .NET are Structs.
9. Better to declare a struct instead of a class when the Total size of all fields is less than
16 bytes (this is not a rule)

Method Overriding vs Method Hiding


Method Overriding Method Hiding
In method overriding, you need to define In method hiding, you just simply
the method of a parent class as a virtual create a method in a parent class
method using virtual keyword and the and in child class you need to
method of child class as an overridden define that method using new
method using override keyword. keyword.
It only redefines the implementation of the In method hiding, you can
method. completely redefine the method.
Here overriding is an object type. Here hiding is a reference type.
If you do not use override keyword, then If you do not use the new
the compiler will not override the method. keyword, then the compiler will
Instead of the overriding compiler will hide automatically hide the method of
the method. the base class.
In method overriding, when base class In the method hiding, when base
reference variable pointing to the object of class reference variable pointing to
the derived class, then it will call the the object of the derived class,
overridden method in the derived class. then it will call the hidden method
in the base class.
https://www.c-sharpcorner.com/UploadFile/8911c4/different-between-method-overriding-method-hiding-new-keyw/

Out vs Ref:
Ref Out
The parameter or argument must be It is not compulsory to initialize a
initialized first before it is passed to parameter or argument before it is
ref. passed to an out.
It is not required to assign or initialize A called method is required to assign or
the value of a parameter (which is initialize a value of a parameter (which is
passed by ref) before returning to passed to an out) before returning to
the calling method. the calling method.
Passing a parameter value by Ref is Declaring a parameter to an out method
useful when the called method is also is useful when multiple values need to
needed to modify the pass be returned from a function or method.
parameter.
When we use REF, data can be When we use OUT data is passed only in
passed bi-directionally. a unidirectional way (from the called
method to the caller method).
It is not mandatory to update all It is mandatory to update all variables
variables passed by ref keyword passed by out keyword inside the
inside the method. method.
Both ref and out are treated
differently at run time and they are
treated the same at compile time.
Properties are not variables,
therefore it cannot be passed as an
out or ref parameter.
From C# 7 it is possible to declare out
parameter inside the method. This
will eliminate the need to split the
usage of C# out variable into two
parts (1. declaration and 2. passing
by ref keyword)

Delegate vs Object
Method called by delegate is faster than method called by object of class.

Delegate invocation are implemented by the .NET runtime.

When a method is called through a delegate, the delegate itself acts as a


wrapper around the method, allowing for dynamic invocation. The delegate
holds a reference to the target method and the object instance (if it's an
instance method). When the delegate is invoked, the .NET runtime performs a
level of indirection to locate and execute the target method.

On the other hand, when a method is called directly through an object of a


class, the method is typically resolved at compile-time. The compiler
determines the exact method to be called based on the static type of the object
and generates the appropriate call instruction.

Const vs Readonly:
Constants have their values set at compile-time and are static, while readonly
fields have their values set at runtime and can differ between instances.
Constants can only be assigned value types or strings, while readonly fields can
be assigned any type.

Constants are generally used for values that are known and won't change, while
readonly fields are used for values that need to be set during runtime and can
vary between instances.
ReadOnly Const
ReadOnly is a runtime constant. Const is a compile time constant.
The value of readonly field can be The value of the const field can't
changed. be changed.
It cannot be declared inside the method. It can be declared inside the
method.
In readonly fields, we can assign values in In const fields, we can only assign
declaration and in the constructor part. values in declaration part.
It can be used with static modifiers. It cannot be used with static
modifiers because it is already
static.

Abstract Class vs Interface


• Method of abstract class can only be implemented using override keyword.
• Method of interface can implemented without override keyword.

• Default access modifier of abstract class's method is private.


• Default access modifier of interface's method is public.
https://www.geeksforgeeks.org/difference-between-abstract-class-and-interface-in-c-sharp/

foreach vs for loop:


• The Foreach loop in C# is not appropriate when we want to modify the
array or collection.

• Foreach works on values of array or list while for loop works on index.

• Foreach only iterates in forward direction while for loop can iterate in both
direction.

• Foreach loop iterates over all elements while for loop only iterates as per
the condition.

• From the performance point of view, the foreach loop takes more time as
compared with for loop. Because internally it uses extra memory space.

• The foreach loop use GetEnumarator() method of the IEnumerable


interface. So, the foreach loop can be used with any class that has
implemented the interface.

Record vs Class:
• Records are designed for the common case of "data only" types. They more
closely resemble structs than classes. A class is an OOP concept that wraps
data with functionality. A record is just a set of data.

• Immutability isn't something that you "prove". It is enforced by the


language. But note that records do not have to be immutable (just like
structs and classes don't have to be). But they are primarily designed for
immutability purposes (hence just a set of related data). Examples might
include points, coordinates or the parts of a complex number. By
themselves the data points mean nothing, but combined together you have
something useful. That is what a record represents.

• To be clear classes can be immutable as well (e.g. strings). But normally


classes allow modifications because they are representing an OOP entity.
Records are just for data storage and have no functionality. Making them
immutable is easy to do with a struct or class. But the new record type
makes it more clear what the purpose of the type is and makes it harder to
get it wrong. Comparing records to structs/classes might lead you to believe
they are the same and they mostly are. However classes are reference types
and follow reference equality. You cannot change that. Records use value
equality which makes them act more like structs.

Static vs Singleton class:


- Static class can't contain non-static method while Singleton class can
contain.
- We can't create object of static class while object of singleton class can be
created.
- We can't inherit interface to the static class while it can be inherited into
singleton class.
- Extension method of static class can't be created while it is possible to
create extension method of singleton class.
Record
30 May 2023 10:28

• It is Immutable Class
• Reference type

public record Member


{
public int ID { get; init; }
public string FirstName { get; init; }
public string LastName { get; init; }
public string Address { get; init; }
}

• init properties are immutable properties which means


member class properties cannot change. What will you
do if you want to add a new property in the Member
class (like the middle name) or change the value of the
address property? The only way is you have to create
new objects and then assign a new value.

• Record can't be static.


Enum
20 April 2023 11:48

• An enum (or enumeration type) is used to assign constant


names to a group of numeric integer values. It makes
constant values more readable, for
example, WeekDays.Monday is more readable then
number 0 when referring to the day in a week.

• An enum is defined using the enum keyword, directly


inside a namespace, class, or structure. All the constant
names can be declared inside the curly brackets and
separated by a comma.

• If values are not assigned to enum members, then the


compiler will assign integer values to each member
starting with 0 by default. The first member of
an enum will be 0, and the value of each successive enum
member is increased by 1.

• You can assign different values to enum member. A


change in the default value of an enum member will
automatically assign incremental values to the other
members sequentially.

• The enum can be of any numeric data type such as byte,


sbyte, short, ushort, int, uint, long, or ulong. However, an
enum can't be a string type.

• You can specify the type after enum name as : type

• Ex. ThreadPriority enum


Size of Clothes (S, M, L, XL, XXL)
From <https://www.tutorialsteacher.com/csharp/csharp-
enum>
Structure
20 April 2023 11:14

• In C#, struct is the value type data type that represents


data structures. It can contain a parameterized
constructor, static constructor, constants, fields,
methods, properties, indexers, operators, events, and
nested types.

• struct can be used to hold small data values that do not


require inheritance, e.g. coordinate points, key-value
pairs, and complex data structure.

• The default modifier is internal for the struct and its


members.

• A struct object can be created with or without


the new operator, same as primitive type variables.

• If you declare a variable of struct type without


using 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.

• A struct cannot contain a parameterless constructor. It


can only contain parameterized constructors or a static
constructor.
Now we can create parameterless constructor in
struct(after C# 10).

• struct is a value type, so it is faster than a class object.


Use struct whenever you want to just store the data.
Generally, structs are good for game programming.
However, it is easier to transfer a class object than a
struct. So do not use struct when you are passing data
across the wire or to other classes.

Notes:
• struct can include constructors, constants, fields,
methods, properties, indexers, operators, events &
nested types.
• struct can implement interfaces, same as class.
• struct cannot inherit another structure or class, and it
cannot be the base of a class.
• struct members cannot be specified as abstract, sealed,
virtual, or protected.

From <https://www.tutorialsteacher.com/csharp/csharp-
struct>
Implicitly-Typed Variables
20 April 2023 10:04

• variables must be declared with the data type. These are


called explicitly typed variables.

• var can be used to declare any built-in data type or a


user-defined type or an anonymous type variable.

• Implicitly-typed variables must be initialized at the time


of declaration.

• Multiple declarations of var variables in a single


statement are not allowed.

• var cannot be used for function parameters.

• var can be used in for, and foreach loops.

• var can also be used with LINQ queries.


Delegates
27 April 2023 10:30

• Reference type data type


• Specialized Class
• Function Pointer (delegate is pointing to the event
handler)
• Intermediate between event raiser and event handler

A delegate in C# is a type that is used to invoke a method.

EventRaiser --> EventArgs --> Delegate --> EventArgs -->


EventHandler

Types:
1. Single cast delegate
2. Multi cast delegate

How to invoke method using delegate:


1. Declare a Delegate
2. Instantiating a Delegate
3. Invoking a Delegate

Uses:
• Multi Threading
• Callbacks
• Event Handling

Method must have same parameters as delegate which is


invoked using object of delegate.
Event
09 May 2023 15:54

https://www.c-sharpcorner.com/UploadFile/puranindia/C-
Sharp-net-delegates-and-events/
Extension Method
Sunday, May 28, 2023 12:12 PM

Two approaches to extending the functionalities of an existing class:


1. Inheritance
2. Extension Method

• Both these approaches can be used for extending the functionalities


of an existing class whereas, in the case of inheritance, we call the
methods defined in the old and new classes by using the object of the
new class whereas, in the case of extension methods, we call the old
and new methods by using the object of the old class.

Need:
• In case of sealed class where inheritance is not possible
• to follow OCP
• used to invoke method of child class from the object of base class
• object of old class can invoke method of new class using extension
method

Points to Remember:
1. Extension methods must be defined only under the static class.

2. We already discussed that Static Class in C# contains only Static


Members. As an extension method is defined under a static class, it
means the extension method should be created as a static method
whereas once the method is bound with another class, the method
changes into non-static.

3. The first parameter of an extension method is known as the binding


parameter which should be the name of the class to which the
method has to be bound and the binding parameter should be
prefixed with this.
4. An extension method can have only one binding parameter and that
should be defined in the first place on the parameter list.

5. If required, an extension method can be defined with normal


parameters also starting from the second place of the parameter list.
Event Redux
27 April 2023 12:13

• Event Redux is a pattern in C# that involves creating a new event that is


triggered when another event occurs. The purpose of Event Redux is to
simplify event handling by reducing the complexity of multiple event
handlers.

• In the Event Redux pattern, a new event is created that is raised whenever
the original event is raised. This new event can be subscribed to by other
event handlers, simplifying the code and reducing the amount of duplicate
code needed to handle events.

public class EventReduxExample


{
private event EventHandler _originalEvent;

// New event that is triggered when the original event


is raised
public event EventHandler NewEvent;

public void RaiseOriginalEvent()


{
_originalEvent?.Invoke(this, EventArgs.Empty);
NewEvent?.Invoke(this, EventArgs.Empty);
}
}

• In the above example, we have a class EventReduxExample with an


original event _originalEvent and a new event NewEvent. When the
RaiseOriginalEvent() method is called, both events are raised using
the ?.Invoke() operator, which checks for null before invoking the event
handlers.

• By using the Event Redux pattern, we can simplify our code and reduce
the amount of duplicate event handling code needed. Other event
handlers can subscribe to the NewEvent event instead of the
_originalEvent event, which reduces the complexity of our code.
File Handling
05 May 2023 17:01

File handling class hierarchy:

Classes of System.IO namespace:


OOP
28 April 2023 11:50

Class: user defined data type that represents


state(properties) and behaviour(methods, action).

Object: instance of Class. Any real time entity.

Inheritance:
Ex.:
Children have rights to their Parent’s Property. As a Child,
tomorrow I can take over my father’s business. I can take
over my Father’s Properties (Car, Buildings, Money, whatever
it is). But I cannot take over my father’s job. The reason is the
Job whatever my father is doing may be based on his
qualifications and his experiences. And tomorrow I cannot
take over his particular job. So, the Job is completely private
to my father. And that is not inherited to me. But remain
everything, business, money, properties, whatever I will take.
Take over everything except the private members.
SOLID Design Principles
08 May 2023 09:47

Need:
• Increase modularity
• Decrease ambiguity
• Reduce coupling
• Increase cohesion
• Increase code readability and understandability

1. Single Responsibility Principle (SRP): The Single


Responsibility Principle in C# states that each software
module or class should have only one reason to change.
In other words, we can say that each module or class
should have only one responsibility to do.

2. Open-Closed Principle (OCP): The Open-Closed Principle


states that software entities such as modules, classes,
functions, etc. should be open for extension, but closed
for modification.

3. Liskov Substitution Principle (LSP): The Liskov


Substitution Principle says that the object of a derived
class should be able to replace an object of the base class
without bringing any errors in the system or modifying
the behaviour of the base class. That means child class
objects should be able to replace parent class objects
without compromising application integrity.

4. Interface Segregation Principle (ISP): The Interface


Segregation Principle states that Clients should not be
forced to implement any methods they don’t use. Rather
than one fat interface, numerous little interfaces are
preferred based on groups of methods with each
interface serving one submodule.

5. Dependency Inversion Principle (DIP): The Dependency


Inversion Principle states that high-level modules/classes
should not depend on low-level modules/classes. Both
should depend upon abstractions. Secondly, abstractions
should not depend upon details. Details should depend
upon abstractions.
Reflection
09 May 2023 11:46

• Reflection is needed when you want to determine or


inspect the content of an assembly. Here, content means
the metadata of an assembly like what are the methods
in that assembly, what are the properties in that
assembly, are they public, are they private, etc.

• For example, one of the biggest implementations of


Reflection is Visual Studio itself. Suppose, in visual studio,
we create an object of the String class, and when we type
obj. then visual studio intelligence shows all the
properties, methods, fields, etc. of that object. And this is
possible because of the Reflection in C#.

What are the real-time uses of Reflection in C#?

1. If you are creating applications like Visual Studio


Editors where you want to show internal details i.e.
Metadata of an object using Intelligence.

2. In unit testing sometimes we need to invoke private


methods to test whether the private members are
working properly or not.

3. Sometimes we would like to dump properties,


methods, and assembly references to a file or
probably show it on a screen.

4. Late binding can also be achieved by using Reflection


in C#. We can use reflection to dynamically create an
instance of a type, about which we don’t have any
information at compile time. So, Reflection enables us
to use code that is not available at compile time.

5. Consider an example where we have two alternate


implementations of an interface. You want to allow
the user to pick one or the other using a config file.
With reflection, you can simply read the name of the
class whose implementation you want to use from
the config file and create an instance of that class.
This is another example of late binding using
reflection.

Note: Reflection is used to find all types in an assembly


and/or dynamically invoke methods in an assembly. This
includes information about the type, properties, methods,
and events of an object. With Reflection, we can dynamically
create an instance of a type, bind the type to an existing
object, or get the type from an existing object and invoke its
methods or access its fields and properties.

So, basically using reflection we can inspect the metadata of


an assembly as well as we can invoke methods are runtime.
There is a keyword called dynamic which was introduced in
C# 4.0 and does the same thing as reflection.
MultiThreading
Tuesday, June 06, 2023 9:55 PM

Namespace to use threading class:


using System.Threading

Classes of threading namespace:


Thread

Thread t1 = new Thread(Method);


==
ThreadStart ts1 = new ThreadStart(Method);
Thread t1 = new Thread(ts1);

Thread is class while ThreadStart and


ParameterizedThreadStart are delegate.

lock()
- to acquire exclusive lock on shared item

Monitor
- to acquire lock using Enter and Exit method in try-catch
block

Mutex
- used to give access of shared resource to external thread
(outside the current process)
- but mutex allows only one external thread to execute at a
time
- The Mutex Class is inherited from WaitHandle abstract
class and the WaitHandle abstract class implements the
IDisposable interface.

Semaphore(initial(available) count, max. count)


- can give access of critical section to multiple external
thread
- initial count = available count
- if we set the maximum count value as 3 and the initial
count value is 0, it means 3 threads are already in the
critical section, so no more new threads can enter the
critical section.
- If we set the maximum count value as 3 and the initial
count value as 2. It means a maximum of 3 threads can
enter the critical section and there is one thread that is
currently in the critical section, so two new threads can
enter the critical section.

SemaphoreSlim
- more than one internal thread can run concurrently.

Thread Pool
- Collection of threads which can be reused whenever
request comes.
- Already used threads will stored in thread pool for reuse.

Types of Thread:
1. Foreground Thread
- thread which continues its execution even if main
application/thread exit or completes its execution.
- it completes only after its assigned task finishes.
- so foreground threads have ability to prevent application
from terminating.

2. Background Thread
- thread which terminated/ quit if main thread
exit/complete its execution.
- IsBackground = true to make thread background.

By default main thread and default thread that we creates is


Foreground thread.
By default threads that are stored in thread pool are
Background threads.
CLR will ends the process when all the foreground threads
finish their execution.

AutoResetEvent
- maintains boolean variable. If false then blocks the
thread otherwise unblock the thread.
WaitOne
- used to block current thread. Returns true if it receives
signal from another thread otherwise returns false.
Set
- release the method from waiting state.
For each WaitOne method there should be a corresponding
Set method in AutoResetEvent.
while for all the WaitOne methods, one Set method is
enough to release in the case of ManualResetEvent.

Thread Life Cycle:


1. Unstarted / New
2. Runnable
3. Running
4. Not Runnable / WaitSleepJoin State
5. Dead

ThreadPriority Enum // example of enum

ThreadPriority:
Lowest, BelowNormal Normal, AboveNormal, Highest

Abort():
- used to terminate thread execution which throws
ThreadAbortException to terminate thread.

Freeze and Thaw the thread while debugging.


Debugging with condition.
Async-Await
Tuesday, June 06, 2023 10:00 PM

Sequential Programming
Concurrency
Multithreading
Parallel Programming
Asynchronous Programming
Multitasking
Determinism & Nondeterminism

Await keyword doesn't block the thread but it freeze the


thread.
That thread will go to serve another waiting task and come
back to previous once waiting time finishes.

Async method returns one of the following types:


1. Task / Task<T> = Promise
2. ValueTask / ValueTask<T>

In asynchronous programming when your method does not


return anything, then instead of using void you can use Task.

To wait for Async method use Value as return type otherwise


use void.

CancellationTockenSource class
- CancleAfter(int ms) method
- TaskCancllationException

Task.CompletedTask, Task.FromResult, Task.FromException,


Task.FromCanceled are used to create synchronous method
using Task.

Retry Pattern:
- retry the process multiple times if it fails.
- if we make an HTTP request to a Web server, sometimes
those operations failed and we may not want
immediately tell the user that there was an error. We
may want to retry the operation just in case the
operation works this time.

Only One Pattern:


- Sometimes we will have multiple tasks, and all the tasks
give us the same information, and we only want to use
the first one to finish and cancel the rest. For that, we can
use Only One Pattern that uses the cancellation token. An
example of this will be if we need to obtain information
from different providers that work asynchronously. And
when we get a response from one, we want to cancel the
other tasks.

Parallel ForEach loop:


- use Action delegate as second parameter.
Misc
04 May 2023 15:12

Shallow Copy: Pointing to address of variable.


Deep Copy: Copying the value of variable.

Design Level Abstraction vs Implementation Level


Abstraction/ Abstraction vs Encapsulation:
• Abstraction, as we’ve seen pertains to hiding underlying
details and implementation in a program. Encapsulation,
on the other hand, describes how abstraction occurs in a
program.

• Abstraction is a design-level process but encapsulation is


an implementation process. Encapsulation tells us how
exactly you can implement abstraction in the program.
Abstraction pertains to only displaying the essential
details to the user whereas encapsulation pertains to
typing up all the data members and associated member
functions into a single abstracted unit.

Association, Aggregation and Composition:


- Composition and Aggregation are two forms of
Association.
- Aggregation follows 'has-a' relationship.
- In aggregation two entities can survive independently.
- Ex. College, Teachers and Students
Employees and Bank
- Composition follows 'part-of' relationship.
- It means two entities can't be exist without each other.
(Highly Dependent)
- Ex. Library and Books
Standard and Students
Car and Engine

Inheritance:
- It follows 'is-a' relationship.
- One thing can be displayed in many form.

You might also like