1. CSharp
1. CSharp
Public
The public keyword is an access modifier for types and type members. Public
access is the most permissive access level.
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.
Accessibility
• Cannot be accessed by object of another class
• By derived classes
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).
Accessibility
Protected Internal
In other words, a protected internal member is accessible from any class in the
same assembly, including derived classes.
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:
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
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 is the term that programmers use in C++. There is a term
"abstract" in place of "pure virtual method" in C#.
Virtual Method
Abstract Method
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.
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.
Instance Method
Static Method
This belongs to the type, it does not belong to instance of the type. You can
access static methods by class name.
Main use of constructor is to initialize the private fields of the class while
creating an instance of the class.
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
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 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.
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.
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()
SortedList:
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
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
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.
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.
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.
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.
• 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.
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.
• It is Immutable Class
• Reference type
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
Types:
1. Single cast delegate
2. Multi cast delegate
Uses:
• Multi Threading
• Callbacks
• Event Handling
https://www.c-sharpcorner.com/UploadFile/puranindia/C-
Sharp-net-delegates-and-events/
Extension Method
Sunday, May 28, 2023 12:12 PM
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.
• 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.
• 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
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
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.
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.
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.
ThreadPriority:
Lowest, BelowNormal Normal, AboveNormal, Highest
Abort():
- used to terminate thread execution which throws
ThreadAbortException to terminate thread.
Sequential Programming
Concurrency
Multithreading
Parallel Programming
Asynchronous Programming
Multitasking
Determinism & Nondeterminism
CancellationTockenSource class
- CancleAfter(int ms) method
- TaskCancllationException
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.
Inheritance:
- It follows 'is-a' relationship.
- One thing can be displayed in many form.