C# Notes
C# Notes
Contents
Solid Principle............................................................................................................................................................................. 3
What is the difference between Build and Rebuild and Clean in C#?................................................................5
What is difference between constructor and function............................................................................................. 6
How can initialize instance variable of class................................................................................................................ 6
Thread Starvation................................................................................................................................................................... 7
what is constant variable..................................................................................................................................................... 7
Integer Literals......................................................................................................................................................................... 7
what is Variables..................................................................................................................................................................... 7
what is default values............................................................................................................................................................ 7
what is Data Types.................................................................................................................................................................. 7
Value types................................................................................................................................................................................ 7
what is an Operators.............................................................................................................................................................. 9
what is Datatype Conversion........................................................................................................................................... 10
Difference between Parse and TryParse..................................................................................................................... 10
Difference between Convert.tostring and tostring................................................................................................. 11
What is array.......................................................................................................................................................................... 11
What is array and array list.............................................................................................................................................. 11
What is decision making if statement.......................................................................................................................... 11
what is switch statement................................................................................................................................................... 12
what is break statement.................................................................................................................................................... 12
What is Continue Statement............................................................................................................................................. 12
What is default statement................................................................................................................................................. 12
what types of comments in c#?...................................................................................................................................... 12
what is Loops......................................................................................................................................................................... 12
What is While loop............................................................................................................................................................... 12
What is Do...While Loop..................................................................................................................................................... 13
What is for Loop.................................................................................................................................................................... 13
What is foreach loop........................................................................................................................................................... 13
Why Methods Need.............................................................................................................................................................. 13
What is methods................................................................................................................................................................... 13
Why we use function or method in a class................................................................................................................. 13
What is Types......................................................................................................................................................................... 14
Page |2
Solid Principle
SOLID principles are the design that enable us to manage most of the software
design problems. Robert C. Martin compiled these principles in the 1990s. These
principles provide us with ways to move from tightly coupled code and little
encapsulation to the desired results of loosely coupled.
No index entries found.
S: Single Responsibility Principle (SRP)
O: Open closed Principle (OSP)
L: Liskov substitution Principle (LSP)
I: Interface Segregation Principle (ISP)
D: Dependency Inversion Principle (DIP)
-Single Responsibility Principle (SRP) This means
that every code, in your class should have only one job to do. Everything in that
class should be related to a single purpose. Every module or class should have
responsibility over a single part of the functionality provided by the software.
interface IUser
{
bool Login(string username, string password);
bool Register(string username, string password, string email);
}
interface ILogger
{
void LogError(string error);
}
interface IEmail
{
bool SendEmail(string emailContent);
}
Open for extension" means, we need to design our module/class in such a way
that the new functionality can be added only when new requirements are
generated. "Closed for modification" means we have already developed a class
and it has gone through unit testing. We should then not alter it until we find
bugs. As it says, a class should be open for extensions. This is achieved using
Abstract Class. The derived class implemented the Abstract class and
abstract method.
This principle is just an extension of the Open Closed Principle and it means that
we must ensure that new derived classes extend the base classes without
changing their behaviour. I will explain this with a real-world example that
violates LSP.
A father is a doctor whereas his son wants to become a cricketer. So here the son
can't replace his father even though they both belong to the same family
hierarchy.
--Thread- Thread is a light weight execution and one processor can have multiple
thread.
--asynchronous Programming-If you have more thread than function this is call
asynchronous programming.
--Async
Async controller are used to improve application performance on the server.
Async controllers are best way to serve multiple request on web server. Basically
used for performance of application. We make Action method asynchronous
Page |7
--Sync
Thread Starvation
----what is literal?
literal are value constants assigned to variables in a program.
default value = 0
----There are two types of Value types
Non nullable-
Nullable types are a feature of the type system of some programming languages
which allow the value to be set to the special value NULL instead of the usual
possible values of the data type Any Datatype can be declared nullable type with
the help of operator "?".
Reference Type- The
reference types do not contain the actual data stored in a variable, but they
contain a reference to the variables. In other words, they refer to a memory
location. Using multiple variables, the reference types can refer to a memory
location. If the data in the memory location is changed by one of the variables,
the other variable automatically reflects this change in value. Example of built-in
reference types are: object, dynamic, interface, class, delegates, arrays and string.
default value = null
on the other hand, when a reference (object) type is converted to a value type, it
is called unboxing. Boxing is implicit conversion and unboxing is explicit
conversion.
Boxing / Unboxing
Reference
what is an Operators?
An operator is a symbol that tells the compiler to perform specific mathematical
or logical manipulations. C# has rich set of built-in operators and provides the
following type of operators:
Arithmetic Operators +-/*%
Relational Operators == != > < >= <=
Logical Operators && || ! & | ^
Assignment Operators =
Increment and decrement Operators ++ --
P a g e | 10
Conditional Operators
Bitwise Operators & | ^ ~ << >>
Misc. Operators sizeof () typeof() & * ? : is as
Ternary Operators ?:
Null Coalescing operator ??
-If the number is in string format but added with any word not valid number then
use TryParse().Exp- “12545HJk”
P a g e | 11
What is array?
If we want to store a group of similar data type in a single variable than we can
use an array, we can add any data type of array. arrays are strongly type nature
arrays cannot grow in size once initialized. array is fixed size and fixed length.
what is Loops?
There may be a situation, when you need to execute a block of code several
number of times, a loop statement allows us to execute a statement or a group of
statements multiple times.
What is methods?
Methods are also called as functions, these terms are used interchangeably,
Methods are extremely useful because they allow you to define your logic once,
and use it, at many places. Methods make the maintenance of your application
easier. A
method is a group of statements that together perform a task. Every C# program
has at least one class with a method name Main.
Methods are the way to how we entertain the variable of the class. It’s wrapper
of the variable.
What is Types?
Classes, structs, enums, interfaces, delegates are called as types. Types can have
only 2 (internal, public) of the 5 access modifiers. Trying to other any modifier for
type we get compile error. So if you don't specify an access modifier for Types the
default is internal.
Public – When type members and types defined as Public, it can be accessed from
any code in the project or anywhere in the project.
Private - When type members defined as Private, it can be accessed by any code
within the containing class or containing types only.
Protected - When type members defined as protected, it can be accessed by any
method in the inherited classes and any method within the same class. If you
want to access base class protected member in derived class, you can use derived
class objects or can use base keyword or also can use this keyword for accessing
base class protected members. The protected access modifier cannot be applied
P a g e | 15
Method Parameters?
Parameters are used to pass values or variable references to methods.
There are four different kinds of parameters in C#:
value parameters (the default),
reference parameters (which use the ref modifier),
output parameters (which use the out modifier), and
parameter arrays (which use the params modifier).
value parameters -
This is the default mechanism for passing parameters to a method. when a
method is called, a new storage location is created for each value parameter.
creates a copy of the parameter passed, so modifications do not affect each
other.
P a g e | 16
reference parameters -
The ref method parameter keyword on a method parameter causes a method to
refer to the same variable that was passed into the method. Any changes made to
the parameter in the method will be reflected in that variable when control
passes back to the calling method.
output parameters - Use
when you want a method to return more than one value. using out parameters
no need to use any return type.
parameter arrays -
The params keyword lets you specify a method parameter that takes a variable
number of arguments. you can send a comma-separated list of arguments, or an
array, or no arguments, params keyword should be the last one in a method
declaration, and only one params keyword is permitted in a method declaration.
What is namespace?
A namespace is used to organize your code and is collection of classes, interfaces,
struct, enums and delegates. “Using” keyword can be used for using the
namespace in other namespace. Namespace can contain, another namespace
class, interface, struct, enums delegate.
What is class?
Class is user defined data type. Class allow you customize as you want. Its logical
structure. A class consists of data and behavior. class data is represented by its
fields and behavior is represented by its method. Every class should have by
default constructer and destructor. Class is just wrapper for variable.
Class is reference type. And variable of the class goes into heap memory.
Agar main class likhta hun aur new nahi lagata hun to oject heap me rahega.
Agar object stack me rahega agar one chance memory leakage ka hai to stack
over flow ho jayega.
Agar class reference type hai to operating system 2 thread dega.ek thread
function execute k liye aur second thread heap memory ko manage karne k liye ya
garbage collection k liye.
P a g e | 17
Aur agar class value type hota to compiler kewal single thread deta. Iska matlab
hai reference type me 2 thread milta hia aur value type me 1 thread milta hia.
Reference type me 1 thread for heap and 1 for stack memory. Stack ko manage
karne k liye separate thread hai aur heap ko manage karne k liye separate thread
hai. Heap ko jo manage karne k liye thread hai use background thrad kehte hai.
Struct hai to single thread ka support hai aur agar reference hai to 2 thread ka
support hai. Refernce karne se stack bhi banta hai aur heap bhi banta hai. Stack
ko manage karne k liye thread hai aur heap ko manage karne k liye thread hai.
Refernce type me hum 2 thread se kehle hai.
---What is object?
Object is class pointer. it points the memory address of the class. where memory
allocated. Object is the mechanism to access the variable which is kept in the
memory or in the class. Object never hold the variable. Object is the way to access
the variable. Object is a variable of user defined data type.
If variable of class goes into block memory that is call instance variable. Even we
can declare static variable in static function. When we allocate the memory of the
class by the new operator we call instance variable.
P a g e | 18
Static variable
Static variable is class level variable so that’s why we can access by class name or
static function, static constructor, static properties. it only can be declaring at
class level. We cannot declare static variable within static function. Static variable
is global variable. Is variable ka object se koi lena dena nahi hai. Static variable
makes a single copy and common for only those who belongs to that class or
belongs to same class.
Static variable don’t support inheritance. Only two type of variable support
inheritance instance variable and instance read only variable.
If we declared variable within a class and when we allocate the memory for the
class and that variable not goes into the block memory of the class.it is static
variable.
-If a class mark as static every member of this class will be static.
-In any situation we cannot create an object of static class.
-If function mark as static it primarily meant for initializing the static variable, not
static read only variable because static read only variable only initialize by static
constructor.
-If function mark as static independent to an object we can call directly call be
class name.
-The purpose of declaring function as static it can return the value that is common
for everyone.
-If function declare as static the outcome of fun is not specific for an object.
P a g e | 19
-Agar kisi class se pehle static laga diye to wo sealed ho gaya. Uska instance nahi
banega. Inheritance nahi hoga.
-Agar kisi class se pehle static lag gaya to new andar aur bahar se kahi se bhi nahi
laga sakte.
-Agar kisi class se pehle static laga diya to wo app domain me jayega.wo CLR k
paas rahega.wo class memory se kabhi terminate hi nahi hoga.jab tak tum apne
app domain ko shut down nahi karoge.ye class HEAP memory me kabhi nahi
jayega.
-Kisi class se pehle static laga rahe ho to intention kya hai? Intention hai helper
class.
-har class ka base class object hota hai.
When static keyword not present in a method than call instance method an
instance method is invoked using an instance of the class means object of the
class.
---What is an Object?
An object is an instance of a class. It contains real values instead of variables. For
example, let us create an instance of the class Employee called “John”.
Employee John= new Employee ();
Now we can access all the methods in the class “Employee” via object “John” as
shown below.
John.setName(“XYZ”);
compiler level because constructor is kind of function and function not return
value it is not possible. Return type is void you can check while using debugger.
Constructor call automatically when we create an instance or object of the class
with the new keyword. Constructor always called before object.
Constructor support static polymorphism. Constructor never be inherited.
Constructor never called explicitly.
-Constructor call every time with new object static constructor call only once and
function call every time with the same object.
if (string.IsNullOrEmpty(connection))
{
throw new Exception("No connection string configured in
Web.Configfile");
}
}
}
Types of constructor?
Default:
Public:
Private:
Static:
Intern:
---What is Default Constructor in C#?
If you do not provide a constructor for a class than .net framework will provide
one constructor for free which is default parameter less constructor. if you want
to control which constructor get call first, then use base keyword front of child
class method. If you give same name, same parameter and same type for the
constructor then it will give compile time error.
P a g e | 22
---Private Constructor?
If any class is having a private constructor it means externally we cannot create an
object of that class. intention behind this that class itself provide you an object as
single responsibility of principle as ownership. Intention is quite clear that class
cannot be instantiated means you cannot create object of this class from outside
of the class.
What is the Couse of this intention? The Couse of this intention is single
ownership. Single responsibility principle as ownership.
Singleton is the best example for private constructor. Single object as a global
object. If any class have private constructor mean that class object is global
object.
Example printer in office just one printer and all the employees using same
printer.
Agar kisi class me private constructor hai to uska bahar se object nahi banega.iske
piche karan kya hai bahar se object q nahi baenga.karan ye hai ki wo class apne
aap me ownership rakhega. issse kya hoga isse lazy loading achieve hoga. Wo
class apne aaphi apni memory banayaga. wo class khud decide karega hum
banyenge object. Wo class sirf ek object banyega aur sare class ko provide karega.
Isse hi kehte hai singleton. Agar kisi class k paas private constructor hai to usse
apne baahar k class se communication k liye static function aur static property
hona must hai.
Lazy loding- agar hum bank jate hai to jab tak manager na aye logo ko paisa nahi
milta. Matlab sabkuch depend hai ek manage par single responsible principle.
Q k chabhi usi ka paas hai.
Agar ek object se sabko object provide kiya jayega to fir ye singlton nahi hai.
Singleton ka matalb hai ki ek hi object banega aur sabhi usi object ko use karenge.
-Matlab saaf hai jab hum class banate hai to us class ko access karne k liye
multiple time object bante hai.har baar new kyeword ka use karke hum object
banate hai.is tarike se ek hi class k multiple object creates karte hai. aur use
object k madat se us class k methods, variable etc. sabhi ko access karte hai. Lekin
apko pata hai jab bhi hum new keyword use karte hai to runtime par ek memory
accupy hota hai jisse hum RAM memory kehte hai. Aur har object primary
memory me jata hai. Aur wo kuch space ko occupy karta hai. Jitna jada space
occupy hoga. Memory full hone ka jada chances hai. Aur performance degrade
hogi.
Isse kya hota hai ki ek hi class k multiple object banye jate hai jisse performance
degrade hota hai.
NOTE-
Pravate
-Private constructor lagane se us class ka Base class ho sakta hai but derived class
nahi ho sakta aur agar class se pehle static laga doge to uska base class bhi nahi
hoga aur derived class bhi nahi hoga. Matlab agar class me static laga dete hai to
uska kahi se bhi object nahi banega chahe andar ho ya bahar ho. Jabki private
constructor lagane par bahar se new nahi lagega lekin class k andar to new laga hi
sakte hai.
-Agar kisi class me private constructor hai to uska internally object banega but
bahar se object nahi banega.
-Agar kisi class me private constructor hai to usme new laga sakte lekin bahar se
nahi laga sakte andar se to new laga hi sakte ho.
P a g e | 24
-Agar kisi class me private contructor hai to usme new lag sakta hai andar se isliye
ye HEAP memory me jayega.
-Kisi class me private constructor hai to intention kya hai. Intention static object
hai as global object known as singleton.
-Agar kisi class me singleton hai to wo static object ka behavior dega.
Static
-Agar kisi class se pehle static laga diye to wo sealed ho gaya. Uska instance nahi
banega. Inheritance nahi hoga.
-Agar kisi class se pehle static lag gaya to new andar aur bahar se kahi se bhi nahi
laga sakte.
-Agar kisi class se pehle static laga diya to wo app domain me jayega. wo CLR k
paas rahega. wo class memory se kabhi terminate hi nahi hoga.jab tak tum apne
app domain ko shut down nahi karoge.ye class HEAP memory me kabhi nahi
jayega.
-Kisi class se pehle static laga rahe ho to intention kya hai? Intention hai helper
class.
---What is Helper class?
In an Object-oriented Programming language, a helper class is used to provide
some extra functionality of the current class. It is special types of class that filled
with a static or non-static method. And an instance of a helper class is also called
a helper object.
--Aisa kon sa function hai jiska return type hona must hai?
Jis class me private constructor hai us class me jo static function uska retunrn
type hona must hai.
Singleton means global object as static object. There are no keywords like a
singleton. Static object and Global object know as singleton. Singleton is logical
perception. singleton is just a behavior. But is you have static object you can
create this behavior.
The static object and global object as known as singleton.as such there is no
singleton. You write a program in such way that you able to create static object
known as global object it behaves as singleton.
Singleton means technically we need to write a code which can give me a static
object.
P a g e | 25
When we write the class and we have several classes in a surrounding. Those
classes which is my surrounding want to go for creating an object of that class. if
the go individually for creating object of that class.
---Intern Constructor?
A class containing an internal constructor cannot be instantiated outside of the
assembly(Namespace).
P a g e | 26
Maintaining the log. Like mobile detect network, which can detect the sim. Which
give a signal. This kind of things run automatically this is called pre this is done by
static.
P a g e | 27
Coming ring tone, making call, opening any application this is post call this is done
by object.
For example
-Static constructors are used to initialize static fields in a class. we can declare a
static constructor by using the keyword static in front of the constructor name.
we cannot use access modifier for static constructor. static constructor is called
only once, no matter how many instances you create, static constructors are
called before instance constructor.
-Agar kisi code ko static constructor me likoge to kya hoga? Wo code sirf ek baar
hi run hoga. Jaise ki log ko maintain karna,
Constructer har baar call hoga ek naye object se,Static constructore ek bar hi call
hoga aur function baar baar call hoga us object se.
Class se jitne partaining information hai ya jitne associate information hai unhe
static constructor initialize karega aur object se jo concern information hai unhe
intialize constructor karega.
Note-
Based on inheritance Agar 2 class hai Base class aur Derived class. Base class
derived class se inherit hai. Aur dono class me static constructor hai. agar main
me kuch nahi hai to compiler kewal derieved class ka static constructor ko call
karega.
P a g e | 28
Jab hum derived class ka memory allocate karenge object banakar tab base class
ka memory load hoga. ab base class ka sataic constructor call hoga aur derived
class ka bhi static constructor call hoga.
P a g e | 29
Agar Base class aur Derived class dono class k pass static constructor aur default
constructor bhi hai. agar aap memory allocate kar rahe hai matlab object bana
rahe hai derived class ka main me to-
-Sabse pehle derived class ka static constructor call hoga.
-Uske baad Base class ka static constructor call hoga.
-Base class ka default constructor call hoga.
-Derived class ka Default constructor call hoga.
Aur agar main me object nahi bana rahe hai ya memory allocate nahi kar rahe hai
to sir
-derived class ka static constructor call hoga.
P a g e | 30
---What is destructor?
A destructor will have the same name as the class name but they don’t take
parameters also cannot have return type, and they have tiled ~ in front of them,
used for clean-up any resources which class holding during the life time,
destructor called automatically to garbage collector for clean-up object memory.
-----oops Inheritance
Polymorphism
Encapsulation Abstraction
----What is inheritance?
P a g e | 32
It allows code
reuse means whatever code is present in a base (Parent class) class that code also
available in derived class (child class) means child class, code reuse can reduce
time and errors.
P a g e | 33
-Stack when build or created? Stack even created when class have functions.
Otherwise stack will not create.
-If class have 3 functions and 4 variables than all function will save in stack
memory and variable will save in Heap memory. If class have not function than
stack memory will not create.
-All things happening at Runtime.
-At a compile time only file compiling. If C#, Then .exe file. If type script .js.
-When we create object 103 address come to 104 and 104 come to 105.this is
inheritance. that’s why we access the function and variable of other class.
-Internally compiler create memory for the base class an address of that memory
has gone to derive class this is inheritance.
-What is virtual object? When you go fir inheritance. Compiler internally. allocate
memory for the base class and memory address has gone to derive class.
---What is Polymorphism?
P a g e | 35
The word polymorphism came from two Greek words ‘poly ‘and ‘morphos ‘.
Here poly means many and morphos means forms.
Polymorphism allow you to invoke derived class methods through a base class
reference variable at runtime, if in the base class the method is declared virtual,
we can override the same method in the derived class. The virtual keyword
indicates the method can be overridden in any derived class.
Console.WriteLine(a + b + c);
}
}
In above class we have two methods with same name but having different input
parameters this is called method overloading or compile time polymorphism or
early binding.
----Example for Compile Time Polymorphism and Example for Run Time
Polymorphism?
Example of Compile Time Polymorphism - Method Overloading
Example of Run Time Polymorphism - Method Overriding
---What is Encapsulation?
The programmer can hide the data and functions in a class from other classes that
is call encapsulation. We can get encapsulation through modifiers like private,
protected, protected internal.
You design the system in a such way that Internal components should not directly
exposed to the user level. If it is than not security at all. So encapsulation concern
to security. Concern to data prevention technic from the user level world.
encapsulation is concern to security, and data prevention from the outside of the
world.
---What is Abstraction?
Abstraction Allows us to define a common definition of a base class that multiple
derived classes can share. Abstraction means you providing only operational part
to the user.
Abstraction means when you hide the internal system to user and how user
operate them? Providing the functionality for performing the operations called
abstraction.
You design the system is such way for example as you sit in the car in front or you.
You have dashboard and you operate AC you don’t know the internal part of the
AC.
Just press the button on and of just only things you know this is call abstraction.
Basically its mean only provides operation part to the user.
P a g e | 38
methodname 2-
Cast child type to parent type and invoke the hidden member
3- ParentClass PC = new ChildClass() PC.HiddenMethod ()
class ParentClass
{
public void DriveType()
{
Console.WriteLine("Right Hand Drive");
}
}
class ChildClass : ParentClass
{
public void DriveType()
{
Console.WriteLine ("Right Hand ")
}
}
----What is Method overriding vs Method hiding ?
In method overriding a base class reference variable pointing to a child class
object, will invoke the overridden method in the child class,
P a g e | 41
In method hiding a base class reference variable pointing to a child class object,
will invoke the hidden method in the base class.
P a g e | 42
-----What is Properties?
Properties allow you to control the accessibility of a classes variables, and is the
recommended way to access variables from the outside in an object oriented
P a g e | 44
---What is structs?
A structure is a value type data type. It helps you to make a single variable hold
related data of various data types. The struct keyword is used for creating a
structure. Structures are used to represent a record.in struct no encapsulation.
Struct does not support object oriented programming language.in struct there is
no scope like private and public. Struct we only used for data structure not for an
application programming interface. And class used for application programming
architecture. every variable in struct by default public
P a g e | 45
---What is attribute?
An attribute is a small amount of information to runtime which tells the
behaviours of various elements like classes, methods, structures, enumerators,
assemblies etc.in the program if we want to add small amount of information to a
program by using an attribute. A declarative tag is depicted by square ([ ])
brackets placed above the element it is used for.
There are two types of attributes:
1. pre-defined attributes
2. custom built attributes.
1-Predefined Attributes
The .Net Framework provides three pre-defined attributes:
Attribute Usage
Conditional
Obsolete
2-Custom Attribute
A new custom attribute should is derived from the System. Attribute class. For
example,
------What is an exception?
An exception is an unforeseen error that occurs when a program is running. An
exception is actually a class that derives from System. Exception class. The
System.Exception class has several useful properties, that provide valuable
information about the exception. Exception is base class but there are many
derived classes available who is responsible for terminating the code while
Exception happening.
Exception is not a runtime error exception is class responsible for abnormal
termination of the program wherever runtime error occurs inside the the
program and class means not a one class there are so many classes derived from
the Exception classes.
finally - Clean and free resources that the class was holding onto during the
program execution.
Specific exceptions will be caught before the base general exception, so specific
exception blocks should always be on top of the base exception block. Otherwise,
you will encounter a compiler error.
Note: It is a good practice to always release resources in the finally block, because
finally block is guaranteed to execute, irrespective of whether there is an
exception or not.
constants and it is called as enumerator lists. Enums are value types in C# and
these can’t be inherited. Below is the sample code of using Enums
E.g. enum Fruits {Apple, Orange, Banana, Watermelon};
-----What is interface?
Interface basically used for finding the common functionality available in multiple
clases of the simmiler type. So we have multiple implementation with the same
signature.
We create interface using interface keyword just like classes. interface also
contains Properties, Abstract methods, Indexer or Events, but only declarations
and no implementation. It is a compile time error to provide implementations for
any interface member. Interface members are public by default, and they don’t
allow explicit access modifiers. Interface cannot contain fields. If a class or a struct
inherit from interface, it must provide implementation for all interface members,
otherwise, we get compile time error. A class or struct can inherit from more than
one interface at the same time, but whereas, a class cannot inherit from more
than one class at the same time.
Interface can inherit from other interface. A class that inherits this interface must
provide implementation for all interface members in the entire interface
inheritance chain.
We cannot create an instance of an interface, but an interface reference variable
can point to a derived class object.
-End point par interface ko expose karne k liye hum interface use karte hai. Taki
hum apne business logic ko hide rakh sake. Hum nahi chahte ki humara business
logic layer expose ho.
-Hum interface ko expose karenge end point par.aur end point k piche chalega
BLL. Hum kabhi expose nahi karenge BLL ko end point par. agar hum end point
par interface ko expose karenge to use function k piche kon si class implement ho
rahi hai ye kabhi expose nahi hoga. Is tarike se hum high level of encapsulation
achieve karte hai.
-By the interface we can segregate the declaration from the implementation.
Abstract
We perceive the behavior of that class. if any class mark as abstract the
perception of that class. or behavior of that class can find in derived class.
If class mark as abstract class, it gives behavior of that class. I can maintain the
versioning.
-If any class mark as abstract. It just consists business logic only for the derived
class.
Interface
We do adons with interface. Interface is contract between class and interface.
-If we want to Implement same signature in different class, then we can use
it. First and foremost, interfaces in C# are a means to get around the lack of
multiple inheritance in C#, meaning you cannot inherit from multiple classes but
you can implement multiple interfaces. ... An interface is a contract between
itself and any class that implements it.
-Interface never gives a behavior of the class. it just a contract.
-By two shirt get one free its interface.
-When we pass interface as constructor parameter or to properties and passing as
method parameter than we can achieve dependency injection. Its call loos
coupling.
-If a class inherits an abstract class, there are 2 options available for that class.
1-Provide implementation for all the abstract members inherited from base
abstract class.
2-If the class does not wish to provide implementation for all the abstract
members inherited from the abstract class, then the class has to be marked as
abstract.
4) An interface can inherit from another interface only and cannot inherit from an
abstract class, where as an abstract class can inherit from another abstract class
or another interface.
----What is delegates?
A delegate is a type safe function pointer. That is, they hold reference(Pointer) to
a function. The signature of the delegate must match the signature of the
function, the delegate points to, otherwise you get a compiler error. This is the
reason delegates are called as type safe function pointers. A Delegate is similar to
a class. You can create an instance of it, and when you do so, you pass in the
function name as a parameter to the delegate constructor, and it is to this
function the delegate will point to.
1-Singlecast Delegate,
2-Multicast Delegate,
3-Generic Delegate
P a g e | 53
Note-
-Delegate also called as function pointer.
-Delegate is reference type.
-We can use delegates without parameter or with parameter list.
-Delegates syntax look very much similar to a method with a delegate keyword.
-Delegate help in code optimization.
-Encapsulating the method’s call from caller.
-Effective use of delegate improve the performance of application.
-Used to call a method asynchronously.
-Signature of the Delegate and Signature of the function should be same.
-Any method that matches the delegate’s signature, which consist of the return
type and parameters, can assign to the delegates.
-In simple words delegates are object oriented and type-safe and very secure as
they ensure that the signature of the method being called is correct.
-Agar hume apne method ko encapsulate karna hai to delegate use karte hai.
-Hum ek hi delegate object k andar multiple method ka reference rakh sakte hai.
-Matlab ek delegate object multiple method ka address rakhta h.
-Delegate has no implementation.
-Delegate can use invoke() method with delegates.
-Delegate is only for declaration not implementation.
Singlecast Delegate-
Singlecast delegate point to single method at a time. In this the delegate is
assigned to a single method at a time. They are derived from System.Delegate
class.
Multicast Delegate-
A Multicast delegate is a delegate that has references to more than one function.
When a delegate is wrapped with more than one method that is known as
multicast delegate. Which means that they can point to more than one function
as a time.
They derived from System.MulticastDelegate class. When you invoke a multicast
delegate, all the functions the delegate is pointing to, are invoked.
data. We can encapsulate a reference to the method inside the delegate object.
Every once in a while you might feel the need to send a method as a parameter to
another
method, and that's when you'll need delegates.
---Difference
between system.string and
system.Text.stringbuilder in c#? The main difference is
system.string is immutable and system.stringbuilder is a mutable. Immutable
means once we created we cannot have modified. Suppose if we want give new
value to old value simply it will have discarded the old value and it will create new
instance in memory to hold the new value.
---Mention
the assembly name where System
namespace lies in C#? Assembly Name –
mscorlib.dll
---What
is the difference between “out” and “ref”
parameters in C#? If you talking about c# function it only
return one value from the function. If you want to return multiple values than we
can use OUT parameter. “ref” parameter has to be initialized
before it is used.
---Hashtable in C#?
It is used to store the key/value pairs based on hash code of the key. Key will be
used to access the element in the collection. For example,
Hashtable myHashtbl = new Hashtable();
myHashtbl.Add("1", "TestValue1");
myHashtbl.Add("2", "TestValue2");
-Stack ko manage karne k liye ek alag thread hai aur heap ko manage karne k liye
alag thread hai. Refernce type me hum 2 thread se kehlte hai.
-Class object created in heap memory and struct object created in stack memory.
--Value Type-
-Value type wo type hai jo struct se milkar bana hota h. aur stack memory me
save hota hai.
-All the primitive type Int, Car, Float, double, byte, Boolean value type are fixed by
value. Whose size are fixed goes to stack memories.
-The size of value types is fixed.
-Values type null value accept nahi karta. Matlab agar int assign kiya hai to use koi
bhi value dena must hai.
-Value type ko variable compile time par milta hai.
-Memory location and values are saved in the same location.
--Reference Type
-A reference type does not store its value directly. Instead, it stores the address
where the values are being stored. In other words, a reference type contains a
pointer to another memory location that holds the data.
-String, Class, object, Delegate, Interface are reference type in c#.
-Reference type wo type hai jo class object se bana hota hai. Aur jiski value heap
me save hoti hai.
-Reference type me hum value ko null assign kar sakte hai.
-Reference type ko variable runtime par milta hai.
Note-Value type contains actual data while reference types contains pointers and
pointers point to the actual data.
Value types are stored on the stack while reference types are stored on heap.
Value types are your normal data types like int, bool, double and reference types
are all objects.
--Heap
P a g e | 63
-Heap ka size stack se bahot bada hota hi. All reference type saves into heap
memory. Reference type k liye heap memory use karte hai.
-We have cache memory, Global memory, Pool Memory, Author memory, Stack
memory, Heap Memory there are multiple kinds of memories in RAM. When we
run the program we need memory.so stack and heap place a measure role for
developing the program and running for the program. Generally, we play with
two kinds of memory.
-Class ka object humesa heap memory me save hota hai.
--Stack
-Stack ka size heap memory se chota hota hai. If fixed by size goes to stack
memory. Value type k liye stack memory use karte hai.
Execution of function goes into stack memory. Wherever it has it always goes into
stack memory. Whose size are fixed goes to stack memories. You are making a
program exception happen, you have taken increased the functions length.
-Within a function we declare variable it also goes to stack memory. Thread run
the functions. Thread is a part of CPU.
-Struct ka object Statck me save hota h.
-By the function declare parameter is also going to stack memory.
-jitna jada length likoge function me utna stack over flow hoga. jitna function se
parameter badhaoge utna stack over flow hoga. ek good programmer function ka
leangth jada nahi rakhta. kyu k use pata hota hai stack over flow kya hota hai.
Hum ek function me jada switch case nahi lagayenge.hum 50 function bana denge
hum 100 function bana denge lekin ek function me sara kaam nahi karenge.ise
kahte hai single responsibility principle.
by that object (as well as calling a clean-up routine, called a "finalizer," which is
written by the user). Some garbage collectors, like the one used by .NET, compact
memory and therefore decrease your program's working set.
The managed heap is the area in memory where reference-typed objects are
allocated.
Managed code is a code whose execution is managed by Common Language
Runtime. ...
C/C++ code, called "unmanaged code” do not have that privilege
Phases of GC
● Marking Phase: A list of all the live objects is created during the marking phase.
● Relocating Phase : Reference for List of Live objects updated
● Compacting Phase : Dead objects released and live objects compacted and
moved.
---What is collection?
Even after object is created, it can be able to modify length and content.
Faster
---Difference
between method parameters and
method arguments?
Method parameters-
A parameter is a variable in a method definition. When a method is called.
Parameter is variable in the declaration of function.
Method arguments-
The arguments are the data you pass into the method's parameters.
Argument is the actual value of this variable that gets passed to function.
---What is Finalizer?
P a g e | 66
These are nothing but class-only methods which will execute before the garbage
collector reclaims the memory for an unreferenced object. To implement finalizer,
you have prefix the symbol (~) before the name of the class.
---What
is the difference between object pooling and
connection pooling?
In case of object pooling, you can control the number of connections. In this case
the pool will decide whether the maximum is reached or not for creation of
objects. If it reached to the maximum level, then the next available object will
have returned back. The drawback is, it increases the time complexity for heavy
objects.
In case of connection pooling, you can control the maximum number of
connections reached. When you are using this pool, since there is nothing in the
pool, still it will create connection on the same thread.
---Five
major topic for oops for basic building block
Instance variable or Member variable.
When we declare a class, class would be several variables. This is the object level
variable. Is save in heap memory.
P a g e | 67
Static variable.
Static read only variable.
Constant variable.
-Dynamic
It checked or decide data type at run time.
Dynamic gives you type capibility.
While using var we get intelligence of datatype.
Errors are caught at runtime
Declaring and initializing both same time not mandatory.
We can change the variable data type later in the code.
Dynamic also maakes alias but it is late binding
I don’t think so programming practice is good for making alias with dynamic
because there is no intelisence, there is no meta data available at design time.
We should use var because we know data type at compile time.
Static Variable-
Static variables are common to all the objects. Each static variable is shared
among all the objects of the same class and they do not tie to a specific object.
A variable that retains the same data throughout the execution of a program.
Constant-
Whenever you declaring a variable using a constant keyword you need to declare
or assigned at the same time. If you not do, then it will give a compile time error.
we will never change the value later in the program once you assign the value for
P a g e | 69
constant. They are implicitly static by default.so we cannot use static keyword
while declaring a variable const. We can apply const keyword to
built-in value type (byte, short, int, long, char, float, double, decimal, bool)
1. Constants can be assigned values only at the time of declaration
2. Constant variables have to be accessed using "Classname.VariableName"
3. Constants are known at compile time
Read-only-
Whenever you declaring a variable using a read-only keyword we don’t need to
initialize at the same time. We can be initialized either at declaration time or in
the constructor. Read only values will evaluate at runtime only. We cannot
change its value at the any point of time using any function. you can’t change its
value.
1. Read only variables can be assigned values either at runtime or at the time of
instance initialization via constructor
2. Read only variables have to be accessed using the
"InstanceName.VariableName"
3. Read only variables are known at run time.
Reference Types
Reference types can inherit from another class or interface.
Reference types are stored on the managed heap.
Reference variables holds only a reference to the location of the object that is
created on the managed heap.
class, interface, delegate, array is the reference type
In reference type there are 2 thread on for executing function and other for
garbage collection.
P a g e | 70
When .net framework receives a request for method call it creates a Thread and
then allocate memory. After that executes the task and once task is completed
Garbage collector removes the thread and free up the memory. So if there are
too many threads then application becomes slow.
---What is Task?
Task work asynchronously manages the the unit of work. In easy words Task
doesn’t create
new threads. Instead it efficiently manages the threads of a threadpool.
---What is Process?
Process is what the operating system uses to facilitate the execution of a program
by providing
the resources required. Each process has a unique process Id associated with it.
You can view
the process within which a program is being executed using windows task
manager.
Chaining Methods?
Chaining Methods, also known as Cascading, refers to repeatedly
calling one method after another on an object, in one continuous line of code.
Output:
Bank Customer …
Loan Customer …
Using interface reference pointing to the Customer class object, class method is
accessible.
IBankCustomer bc = new Customer();
bc.GetCostomerInfo();
Using the class reference pointing to the class object, you can’t access the method
e.g.
Customer c = new Customer();
c.GetCostomerInfo();
what is difference between .NET and c#?
.net is framework and c# is programing language. If you talking about c# it has
syntax, it has grammar, it has semantic. It has for loop, it has if condition. .net has
collection of library and it has run time. .net framework help to run your
applications.it has CLR.it has garbage collector.it has CTS, it has CLS.
Difference between .Net framework and .Net core?
.Net framework
It is only for windows.
it is slow as compare to .net core. If you see .net framework. We have big big dll’s
like system, system. Data but if you talking about .net core it Brocken down every
dll. In .net core they taken big big dll and Brocken down in small small peaces.
Than it will load only those which need. It will not load unnecessary things.
.Net Core
It is cross platform. It full CLI command support.
What is IL (Intermediate Language) Code?
As we know very well when c# program run it convert into machine language.
When compiler compile it converted into machine language. first it converts
partially code known as IL code and then you run your program than time c-omes
JIT. and JIT runs you IL code and compile it into machine language.
What is the benefits of compiling in to IL code?
The run time environment and development environment are totally different. So
depending on the runtime environment JIT compile the best optimized code as
per the environment.
Abstraction vs Encapsulation
P a g e | 78