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

C# Notes

This document contains definitions and explanations of various concepts in C# programming such as data types, variables, operators, decision making statements, loops, methods, classes, objects, inheritance, polymorphism, interfaces, and more. It discusses key differences between related concepts like Build vs Rebuild vs Clean, constructor vs function, value types vs reference types, and provides examples of how to implement certain features like initializing instance variables, handling method parameters, and implementing interfaces with same methods.

Uploaded by

Akash Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

C# Notes

This document contains definitions and explanations of various concepts in C# programming such as data types, variables, operators, decision making statements, loops, methods, classes, objects, inheritance, polymorphism, interfaces, and more. It discusses key differences between related concepts like Build vs Rebuild vs Clean, constructor vs function, value types vs reference types, and provides examples of how to implement certain features like initializing instance variables, handling method parameters, and implementing interfaces with same methods.

Uploaded by

Akash Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Page |1

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

What is Type members...................................................................................................................................................... 14


What is class member......................................................................................................................................................... 14
What is the difference between Types and Type Members................................................................................ 14
What are the Access Modifiers member in C#.......................................................................................................... 14
Method Parameters............................................................................................................................................................. 15
---Difference between a Class and an object.............................................................................................................. 20
Method parameters............................................................................................................................................................. 66
Instance variable or Member variable......................................................................................................................... 67
Loosely Couple and Tight Couple................................................................................................................................... 73
Chaining Methods?............................................................................................................................................................... 73
Chaining Methods,................................................................................................................................................................ 73
Loosely Couple and Tight Couple................................................................................................................................... 73
Why is the Main() method use in C# static................................................................................................................ 74
What is indexing................................................................................................................................................................... 74
How to implement two interface with same method............................................................................................ 74
what is difference between .NET and c#?................................................................................................................... 76
Difference between .Net framework and .Net core................................................................................................. 76
What is IL................................................................................................................................................................................. 76
What is the benefits of compiling in to IL code........................................................................................................ 76
What is the use of JIT(Just in time compiler)?.......................................................................................................... 76
Does .NET support multiple language.......................................................................................................................... 77
What is CLR............................................................................................................................................................................. 77
IEnumerable vs IQueryable.............................................................................................................................................. 77
What is string interpolation............................................................................................................................................. 77
Difference between string and String.......................................................................................................................... 78
What is reflection in c#...................................................................................................................................................... 78
Page |3

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 Closed Principle (OSP) In


object-oriented programming, the open/closed principle states that "software
entities such as classes, modules, functions, etc. should be open for extension, but
closed for modification".
Page |4

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.

-Liskov substitution Principle (LSP) The


Liskov Substitution Principle (LSP) states that "you should be able to use any
derived class instead of a parent class and have it behave in the same manner
without modification". It ensures that a derived class does not affect the
behaviour of the parent class, in other words, that a derived class must be
substitutable for its base class.

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.

-Interface Segregation Principle (ISP) The Interface Segregation Principle states


"that clients should not be forced to implement interfaces they don't use. Instead
of one fat interface, many small interfaces are preferred based on groups of
methods, each one serving one submodule.".
This means, instead of one fat interface many small interfaces.

-Dependency Inversion Principle (DIP)


The Dependency Inversion Principle (DIP) 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.
---What dependency injection?
Page |5

Dependency injection is technique in programing language to avoid tight coupling


architecture. It should be loose coupled.it is used for auto instantiation. You
design the system in such way that I can preventing a to writing new operator and
I can move for the calling to function.
You give responsibility to someone for auto instantiation. I should not participate
for creating the instance.
Dependency injection is technique to achieve decoupling which comes under IOC
principle. What IOC principle? How we can customize flow of control.
–Dependency injection ka matlab hota hai ki jo humare controller class hai aur jo
business layer hai unke bich me tightly coupled na karke loosely coupled rakhte
hai. Hum controller k constructor se Interface pass karte hai jisse hume DI achieve
hota h. -
Hum kitne tarike se dependency injection ko resolve/use kar sakte hai ?
Constructor, Method, Property -
Agar dependency injection nahi hai to kya problem ho sakta ha?
Tightly coupled. controller ko
pata hoga ki code kaha written hai to wo business layer k sare method access kar
lega. –Ek config file
banegi us config file k andar hum decide karenge ki is IStudent interface ko kon si
class implement karegi. Isse fayada ye hoga ki controller class ko nahi pata hoga ki
IStudent interface kon si class implement karegi aur kis class k andar logic likha
hua hai.
Note-
-install unit library from neu get package manager.

What is the difference between Build and Rebuild


and Clean in C#?
-Build Build will look at the files that have been modified and it will only build
code files which have changed.it will never build those files which not modified.
-Rebuild will recompile everything. This will delete all currently compiled files
(i.e., exe and DLLs) and will build everything from scratch, irrespective of if there
is code change in the file or not.
-Clean it goes and delete all compile files and dll from your class library.
Page |6

--Thread- Thread is a light weight execution and one processor can have multiple
thread.

--Synchronous Programming-If you have 4 functions and one thread.


There is 4 function and 1 thread this call synchronous architecture. Its call one
after one. When we write a function is

--asynchronous Programming-If you have more thread than function this is call
asynchronous programming.

What is difference between constructor and function?


Constructor initialize only once and function many times.

How can initialize instance variable of class?


There are several ways of initialize the instance variable of the class.
Constructor,
Function,
Properties,
Object.Variable,

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

what is constant variable?


The variable whose values do not change during the execution of a program
known as constants. Constants can be of any of the basic data types like an
integer constant, a floating constant, a character constant, or a string literal.
There are also enumeration constants as well. Constants are defined using the
const keyword.
Integer Literals?
An integer literal refers to a sequence of digits, there are two types of integer
decimal integers and hexadecimal integers.
what is Variables?
A variable is an identifier that denotes a storage location use to store a data
value. Every variable has a type that determines what values can be stored in the
memory.
what is default values?
A variable is either explicitly assigned a value or automatically assigned a default
value.
what is Data Types?
Every variable in c# is associated with data type. Data types specify the size and
type of values that can be stored
The variables in C#, are categorized into the following types:
Value types
Reference types
Pointer types
Value types
Value type variables can be assigned a value directly. They are derived from the
class System.ValueType. The value types directly contain data. Some examples are
int, char, and float, double, struct, enums which stores numbers, alphabets, and
floating point numbers, respectively. When you declare an int type, the system
allocates memory to store the value.
Page |8

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

Object Type The


Object Type is the ultimate base class for all data types in C# Common Type
System (CTS). Object is an alias for System.Object class. The object types can be
assigned values of any other types, value types, reference types, predefined or
user-defined types. However, before assigning values, it needs type conversion.
When a value type is converted to object type, it is called boxing and on the other
hand, when an object type is converted to a value type, it is called unboxing.
Dynamic Type We
can store any type of value in the dynamic data type variable. Type checking for
these types of variables takes place at run-time.
String Type The
String Type allows you to assign any string values to a variable. The string type is
an alias for the System.String class. It is derived from object type. The value for a
string type can be assigned using string literals in two forms: quoted and
@quoted.
Pointer Type
Pointer type variables store the memory address of another type. Pointers in C#
have the same capabilities as the pointers in C or C++.

---What is boxing and unboxing?


When a value type is converted to reference (object) type it is called boxing and
Page |9

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 ??

what is Datatype Conversion?


When we convert a data of one type to another type before it is used is known as
Type Casting or Type Conversion
Type Conversion has two types
Implicit type conversion
Explicit type conversion
Implicit type conversion - Implicit conversion is those always succeed, this
conversion can always be performed without any loss of data, this conversion
from smaller to larger integral types and conversions from derived classes to base
classes. This conversion also known as automatic type conversion.
Explicit type conversion - These conversions are done explicitly by users using the
pre-defined functions. Explicit conversions require a cast operator.

Difference between Parse and TryParse?


If the number is in a string format you have 2 options - Parse () and TryParse ()
-Parse () method throws an exception if it cannot parse the value, whereas
TryParse () returns a bool indicating whether it succeeded or failed.
9+517-If the number is in string format use parse method. Exp “1000000”

-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

Difference between Convert.tostring and tostring?


values even if variable value become null but “variable. ToString ()” will not
handle NULL values it will throw a NULL reference exception error. So as a good
coding practice using “convert” is always safe. The basic difference between them
is the Convert function handles NULLS while i. ToString () does not; it will throw a
NULL reference exception error. So as good coding practice using convert is
always safe. You can create a class and override the toString method to do
anything you want.

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 array and array list?


If you talking about array list than size are flexible and most important things is
not strongly type. If you talking about performance than array is much better than
array list because array is strongly type. Array list is slower than array because of
Boxing and Unboxing.

What is decision making if statement?


If statement is powerful decision-making statement and is used to control the
flow of execution of statements.it is a two-way decision statement and is used in
conjunction with an expression.
P a g e | 12

what is switch statement?


The switch statement tests the value of a given variable against a list of case value
and when a match is found, a block of statements associated with that case is
executed.

what is break statement?


A Break statement breaks out of the loop at the current point or we can say that it
terminates the loop condition.

What is Continue Statement?


A Continue statement jumps out of the current loop condition and jumps back to
the starting of the loop code.

What is default statement?


The default is an optional case. When present, it will be executed if the value of
the expression does not match any of the case values.

what types of comments in c#?


Single line comments //
multi line comments /* */
XML documentation comments ///

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 While loop?


It repeats a statement or a group of statements while a given condition is true. It
tests the condition before executing the loop body. This process is repeated as
long as the condition evaluates to true.
Note- Don't forget to update the variable participating in the condition, so the
loop can end, at some point,
P a g e | 13

What is Do...While Loop?


A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.

What is for Loop?


A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.

What is foreach loop?


A foreach loop is used to iterate through the items in a collection
Example-foreach loop can be used with arrays or collections such as arraylist,
hashtable and generics.

Why Methods Need?


Methods are very useful that you to define your logic once and uses it many
places.

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.

Why we use function or method in a class?


We cannot perform any kind of operation over the variable while declaring in the
class without function.
Function is How we entertain the variable of the class. function is wrapper of the
variable. Even you make function you.
-Hum jis variable ko class me declare karte hai usse next line me dekh nahi sakte.
Function class variable ko entertain karne k liye hota hai.
P a g e | 14

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.

What is Type members?


Fields, properties, constructors, methods etc., that normally reside in a type are
called as type members. So if you don't specify an access modifier for Type
member the default is private.

What is class member?


Fields, properties, constructors, methods etc., that normally reside in a class are
called as class members.

What is the difference between Types and Type


Members? In general classes, structs, enums,
interfaces, delegates are called as types and fields, properties, constructors,
methods etc., that normally reside in a types are called as type members.

What are the Access Modifiers member in C#?


Different Access Modifier are - Public, Private, Protected, Internal, Protected
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

to classes and interfaces. Methods and fields in an interface can’t be declared


protected.
Internal – When type members and types defined as internal, it can access
anywhere within the containing assembly only. If we want to access this outside
from the assembly, we get compile time error.
Protected Internal – When type members defined as Protected internal, it can be
access anywhere within the containing assembly, or from within a derived class in
another assembly. It is a combination of protected and internal. If you have
understood protected and internal, this should be very easy to follow.
Access Specifier: This determines the visibility of a variable or a method from
another class.
Return type: A method may return a value. The return type is the data type of the
value the method returns. If the method is not returning any values, then the
return type is void.
Method name: Method name is a unique identifier and it is case sensitive. It
cannot be same as any other identifier declared in the class.
Parameter list: Enclosed between parentheses, the parameters are used to pass
and receive data from a method. The parameter list refers to the type, order, and
number of the parameters of a method. Parameters are optional that is, a
method may contain no parameters.
Method body: This contains the set of instructions needed to complete the
required activity.

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.

Sabhi class me by default internally constructor aur distractor hota hai.


Constructor basically class k instance variable ko initialize karne k liye hota hai.

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 instance variable or member variable ?


Declare the variable at class level it set to be member variable or instance
variable.

---What is member function?


Declaring any function within a class it set to be member function.

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

--What is the deference between variable and object?


Variable refer to a primitive type and object is refer to a user defined data type.

---What is instance variable and static variable?


Instance variable
Instance variable is object level variable and we declare only at class level. Only by
the object we can initialize. We can initialize by the constructor. We can initialize
by the functions.

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.

---What is deference between variable and object?


Variable refer to privative type and object refer user defined data type. Object is a
variable of user defined data type.

---What is static class?


When static keyword used on a class declaration enforces that the class cannot
be inherited and that all the members of the class are static in nature. A static
class can only have static members. you cannot declare instance members
(methods, variables, properties, etc.) in a static class.
static class cannot have base class as well as derived class? except object is base
class of static class.

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

---Why do we need static class in C#?


The advantage of using a static class is that the compiler can check that no
instance members are added. The compiler will guarantee that instances of
this class cannot be created. Static classes are sealed and therefore cannot be
inherited. They cannot inherit from any class except Object.

---What is Recursive Method Call?


A method can call itself. This is known as recursion.

---What is static method?


When method declaration includes a static modifier, that method is called a static
method. we cannot create object for a class when static modifier is present. we
can call static method using by class name.

---When should we use static methods in C#?


Use a static class to contain methods that are not associated with a particular
object. For example, it is a common requirement to create a set of methods that
do not act on instance data and are not associated to a specific object in your
code. You could use a static class to hold those methods.

---What is instance method?


P a g e | 20

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.

---Difference between static and instance method?


When method declaration includes a static modifier, that method is called a static
method. we cannot create object for a class when static modifier is present. we
can call static method using by class name.
Where 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”);

---Difference between a Class and an object


Class:
1)Class is a datatype that contains the programming logic.
2)Class is visible in the source code and resides in hard disk.
3)Class is like a template of the object. It implements reusability, encapsulation,
inheritance
Object:
1)Object is a chunk of memory that implements the class logic.
2)Object is in the RAM and not visible in source code.
3)Object is the real world implementation of the class.

---What is a Constructor in C#?


A constructor is a special kind of function.it is used for initializing instance variable
as well as instance read only variable.it provide data to object. A constructor will
have the same name as the class name. base class fields, constructor can take
parameters but it cannot return value to a user level but it returns a value to a
P a g e | 21

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.

public class UserDal


{
static UserDal()
{
Connection =
ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;

if (string.IsNullOrEmpty(connection))
{
throw new Exception("No connection string configured in
Web.Configfile");
}
}
}

UserBal _userbal = new UserBal();

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.

Best example printer.

Private constructor is used to prevent a class to be instantiated. But, if a class has


other public constructors, then that can be instantiated. Private constructor is
used for controlling the object generation which Is singleton design pattern
implementation.
P a g e | 23

--Singleton Pattern-If I created private constructor for the class it means we


preventing to others for new operator for my class. intention is quite clear it
means we preventing instantiation control. If any class have private constructor it
means that class never be a member function. that class never be derived class.
Agar kisi class ka 2 object deferent- deferent location ko point kar raha hai to fir
ye singleton nahi ha. Private constructor rakhne ka matlab hai ki wo class agar
object deta hai to jitna bi object dega sabhi object ka location same hona chahiye
tabhi ye singleton design ko follow karega.
Agar kisi class me private constructor hai aur agar us class se communicate karna
hai to us class me static function aur static property hona must hai. Aur us
function ka return type hona must hai. Aur us function ka return type us class ka
naam hi hona chahiye.

-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

---Static constructor in C#?


Static constructor is special kind of constructor which runs before main function.
That’s why it is special constructor. If we talking about other constructor like
instance constructor, copy constructor, private constructor, default constructor.
All constructer basically concerns to an object.so those constructors will be
executed after the new operator. That’s why it is special constructor because it
runs before main. We don’t have controlling of execution of static constructor.
There is no controlling in my hand and my end. Static constructor call by compiler.
Static constructor is meant for initializing static read only variable.

-static constructor call only once.


-If constructor mark as static. It is free from an object. Because if constructor
mark as static. It calls before main function.
-Static constructor is an independent to an object. Also no involvement of new
operator.
-In a single class we cannot more than one static constructor.
-Static constructor never overload. We cannot pass parameter to static
constructor. -We cannot use access modifier before static constructor. Static
constructor used for initializing only static variable and static read only
variable.no involvement of object and new operator for initializing or calling static
constructor.
-If you want some functionality run automatically than you can use static
constructor. We can also maintain the log as well.
We load system library using static constructor.
-Purpose of using static constructor is some program should trigger automatically.
-Static constructor se pehle koi bi scope nahi ho sakta. You can’t define any scope.
-Static constructor se hum system library load karte hai.

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

---Static constructor aur normal constructor me kya fark


hai?
Normal constructor har baar call hoga jab ek naya object banega.

---What is instance object and static object?


Static object or variable which makes single copy.
Instance object or variable which makes separate or multiple copy.

---What is constructor overloading?


A Constructor can be overloaded in C#. Overloaded constructors are
differentiated on the basis of their type of parameters or number of parameters.
Constructor overloading is not much different than method overloading. In case
of method overloading you have multiple methods with same name but different
P a g e | 31

signature, whereas in Constructor overloading you have multiple constructor with


different signature but only difference is that Constructor doesn’t have return
type in C#

---Ek class me kitne prakar k constructer aur function ho sakte hai?


-Functions there are 6 types of function in the single class.
Class or constructoer level- defauld constructoer, paramitrizr construcert, copy
constructor, shaello copy constructor
Object level-member function, operator function virtual function, abstract
function,
---What is this Keyword?
This keyword actually refers to an object of the class. this keyword is used for
reference of the class or creating object for a class.

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

--What is static and instance class members?


When a class member includes a static modifier, the member is called as static
member. When no static modifier is present the member is called as non static
member or instance member. static members are invoked using class name,
whereas instance members are invoked using instances(objects)of the class.
class member- fields, method, properties, events, indexers, constructors.
An instance member belongs to specific object of the class. If I create 3 object of a
class, I will have 2 sets of instance member, where as there will ever be only one
copy of a static member.no matte how many instances of a class created.

-----oops Inheritance
Polymorphism
Encapsulation Abstraction

----What is inheritance?
P a g e | 32

Inheritance is based on generalization principle. and there is generalization


principle we can go for classification. It is logically categorizing.
Inheritance is based on is a relationship. Inheritance means there is logical
association. So we can say derived class is belonging to base class. in case of
inheritance we can go logically classification between two class base class and
derived class. Its memory referencing between two objects.
We achieve high level of encapsulation through inheritance.
Note-
Derived object = new Derived
In Case of Inheritance When we allocate memory for the derived class, compiler
internally first allocate the memory for the base class. due to memory allocation
of the base class first it calls base class default constructor than derived class
default constructor.
That’s why we achieve high level of encapsulation through inheritance. Because
we don’t know how base class background memory allocated. Who is visible
abstraction and behind the person who making you encapsulation. For example,
Television tube is encapsulation and Television is abstraction.
Through inheritance we can see derived class this is abstraction object dot we can
achieve base class function this is encapsulation

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

-No Difference between inner join and inheritance.


-First memory for employee class will be created.
-Column (:) means Employee: India, Manager: Employee should be common
relationship.
-First India memory 103 will allocate than Employee 104 and last Manager 105
memory will be allocate.
-In background there will be 2 memory allocated first for 103 and second for 104.
-103 and 104 will be virtual object.
-All memory will be save in Heap
-All Object will save in stake
-All variable (int, string, double etc.) will be save in Heap memory.
-All function will be save in Stack memory. Function execution in stack memory.
-If India class have 4 function and 3 variables than all 4 function will go in 103
heap memory and all 3 variables will go in 103 stack memory.
-if Employee class have 16 variables and 2 function than 16 variables will go in 104
heap memory and 2 function will go in 104 stack memory.
-All three class stack is different.
-When we use new keyword it saves Heap memory only. It means only created
heap memory.
P a g e | 34

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

In this example derived class inherits from parent class.


C# supports only single class inheritance.
C# supports multilevel inheritance. C#
supports multiple interface inheritance.
Child class is a specialization of base class.
Base classes are automatically instantiated before derived classes.Parent class
constructor executes before child class constructor

---What is virtual Object in inheritance?


Internally compiler create a memory for the base class an address of that base
class memory going to derived class this call virtual object. When the base class
memory allocated this call virtual object.it internally save In heap memory

---What is Polymorphism?
P a g e | 35

polymorphism basically used for enhancing the object capabilities.


It means we can do multiple activity with same object. One object can do many
things this is call polymorphism.

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.

There are two types of polymorphism


Compile time polymorphism: (Early Binding or Method or Function or Operator
overloading or Static Binding)
Run time polymorphism: (Late Binding or Overriding or Dynamic Binding)

----Compile Time Polymorphism?


Compile time polymorphism means we will declare methods with same name but
different signatures because of this we will perform different tasks with same
method name. compile time polymorphism means same method names with
different signatures (different parameters)
public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
P a g e | 36

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.

---- Run time polymorphism?


Run time polymorphism means same method names with same signatures. We
can override a method in base class by creating similar function in derived class
this can be achieved by using inheritance principle and using “virtual & override”
keywords.
In base class if we declare methods with virtual keyword then only we can
override those methods in derived class using override keyword
//Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
P a g e | 37

DClass objDc = new DClass();


objDc.Sample1();
// calling the base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}
If we run above code, we will get output like as shown below
Syntax : Employee Ram = new Manager();

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

----Define OOPS. What are its benefits?


It is a programming methodology in which the programs are organized as
collections of objects. Each object represents an instance of some class. The
classes can be interrelated to each other through inheritance
OOPS revolves around these concepts:
1)Class
2)Object
3)Inheritance
4)Polymorphism
5)Abstraction
6)Encapsulation
Advantages:
1)Code reusability: define a class and n number of objects implement the class
logic: example: Button class and n number of Button objects
2)Inheritance : Eliminates redundant code and extend the use of existing classes.
example: 1) we can create our own Textbox by inheriting from the Textbox class.
2)We can inherit one Windows Form into another.
3)Encapsulation: The programmer can hide the data and functions in a class from
other classes. It is accomplished through modifiers like private, protected,
protected internal.
4)Easy to Maintain and Upgrade:
If we want to make changes in a class, we can make them and save the changes in
the .dll This .dll can easily be updated in the client by using Update Reference.

5)Polymorphism provides us with methods extensibility.


we can have different methods with same name, but with different kinds of
behavior ex:
Console.WriteLine("welcome");
Console.WriteLine(100);
6)Abstraction allows us to define a common definition of a base class
that multiple derived classes can share.
For example,
create an abstract class bank with simple interest function
This function will be implemented in the derived classes of
the bank class.
P a g e | 39

ex: 1)icici class will have its own simple interest.


2)ABC class will have its own simple interest.
icici and ABC both are child classes of bank class.

-----What is early binding and late binding?


Calling a non-virtual method, decided at a compile time is known as early binding.
Calling a virtual method (Pure Polymorphism), decided at runtime is known as late
binding.

-----What is virtual method?


The virtual method indicates the method can be overridden in any derived class.
It can be applied to methods, properties, indexes, events

---What is method overriding in c#?


To extending the functionality of base class. Means derived class redefine the
same base class function in derived class. To override a base class method which
is defined as virtual, Override keyword is used. In the above example, method
Drive Type is overridden in the derived class. we achieve method overriding by
runtime polymorphism. Best example base is closed for modification and derived
is open for modification. Object of base class is able to call the identical function
of derived class. it just could be possible when derived class extending the
behavior of base class. if there is extendibility there will be runtime
polymorphism.

---How's method overriding different from overloading?


When overriding, you change the method behavior for a derived class.
Overloading simply involves having a method with the same name within the
class.

---What is Method Hiding in C#?


If the child class also have the same method with same signature as parent class
method name than child class method will hide the parent class method This is
called Method Hiding. If you hide intentionally than use new keyword with child
class method.
Note- Different ways to invoke hidden base class member from derived class
1-if you want to invoke base class hidden method use base keyword with
P a g e | 40

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

----Difference between Encapsulation and Data


hiding?
Data Encapsulation is nothing but grouping up of related members (variables and
methods) into a single unit called class
Data Hiding is nothing but restricting outside access of a class members using
access modifiers such as private , protected and internal etc.

---what is data hiding?


Object. Variable should not accessible. means none of the variable should not
visible by the object at any setuation.

---Deference between an abstract method & virtual method?


An abstract method does not provide an implementation and forces overriding to
the derive class (unless the deriving class also an abstract class),
Whereas the virtual method has an implementation and leaves an option to
override it in the deriving class.
P a g e | 43

-----What is method or function overloading?


Method overloading allows a class to have multiple methods with the same name,
but with a different input signature. Means providing multiple set of operations to
a single function.is a best example of method overloading. method in c# function
can be overloaded based on the number, type (Int, float etc.) and kid (value, ref or
out) of parameters.

---What is operator overloading?


Providing multiple set of operators to an object so object can have support
arithmetic operators but in case of method overloading parameters matters
return type never matters. Where in case of operator overloading operator is
function. The return type of function should be must. Function should be static.
And scope of the function must be public.

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

programming language.it can't take any parameters, a property consists of 2


parts, a get and a set method, wrapped inside the property: If there are no
additional logic in the properties then we can use auto implement properties.
When we use auto implement properties, then compiler create a private field,
that can only be accessed through the get and set accessories.
-Properties help for making a model.
-Properties can be inherited. -
Properties can be virtual.
–Properties can be abstract.
-Properties cane be read only. -
Properties support serialization, view state is best example of serialization.
–Properties cannot be overloaded.
-Properties are used for validating the business rules.

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

Message: Gets a message that describes the current exception


Stack Trace: Provides the call stack to the line number in the method where the
exception occurred.
We use try, catch and finally blocks for exception handling.
try - The code that can possibly cause an exception will be in the try block.
catch - Handles the exception.
P a g e | 46

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.

--What is the difference


between Compile Time
Exception and Runtime Exception?
Where we developing an application There are two types of errors
-Compile Time Errors.
An error occurs due to syntactical mistakes we compile time error. Example you
forget semi column, curly braces not proper closed, string not in double cotes.
This kinds or errors not a dangerous because we recognize this kind of errors after
compiling and fixed it quickly.
-Runtime Errors
This kinds of errors occurs at the time of execution your code, this kind of errors
occurs due to various reasons. Examples wrong implementation of logic, wrong
input supplied.

---What is the difference


between System exceptions and
Application exceptions?
-System exceptions are deriving directly from a base class
System.SystemException. A System Level Exception is normally thrown when a no
recoverable error has occurred. This happened by CLR
-Application exceptions can be user defined exceptions thrown by the
applications. If you are designing an application that needs to create its own
exceptions class, you are advised to derive custom exceptions from the
System.ApplicationException class. It is typically thrown when a recoverable error
has occurred. This exception is throw by developer
--What is the difference between Error and Exception?
---What is enum in C#?
enum keyword is used for declaring an enumeration, which consists of named
P a g e | 47

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.

---When to Use interface or abstract class?


There is no comparison between interface and abstract class. both are totally
deferent things. Don’t compare between both. An abstract class allows you to
create functionality that subclasses can implement or override. An interface only
allows you to define functionality, not implement it.
P a g e | 48

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.

---What is abstract Method?


Abstract method doesn’t provide the implementation & forces the derived class
to override the method.

----What is abstract classes?


An abstract class is an incomplete class or special class we can't be instantiated.
The purpose of an abstract class is to provide a blueprint for derived classes and
set some rules what the derived classes must implement when they inherit an
abstract class.
We can use an abstract class as a base class and all derived classes must
implement abstract definitions. An abstract method must be implemented in all
non-abstract classes using the override keyword. After overriding the abstract
method is in the non-Abstract class. We can derive this class in another class and
again we can override the same abstract method with it.
An abstract class cannot be instantiated.
P a g e | 49

An abstract class can contain abstract as well as non-abstract methods.


An abstract method cannot have it implementation in abstract class itself.
An abstract class can never have a sealed modifier, because it is opposite to the
abstract class, an abstract class is created to inherit while a sealed class cannot be
inherited.
A class cannot be inherited from multiple abstract classes but from multiple
interfaces.
An abstract cannot be inherited from a class and multiple interfaces.
A property can also be abstract in an abstract class.
An abstract method is by default a virtual.
An abstract method can only be declared in an abstract class.
All derived classes must implement all the abstract methods in it.
An abstract class can inherit from a class and one or more interfaces.
An abstract class can implement code with non-Abstract methods.
An Abstract class can have modifiers for methods, properties etc.
An Abstract class can have constants and fields.
An abstract class can implement a property.
An abstract class can have constructors or destructors.
An abstract class cannot be inherited from by structures.
An abstract class cannot support multiple inheritance.

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

----What is difference between abstract classes vs


interface? 1)We can’t implement
Interface members but we can implement some Abstract classes of members
(methods).
2) Interface member’s public by default and can’t have access modifier where as
abstract class member private by default. can have access modifier.
3) Interfaces cannot have fields where as an abstract class can have fields.
P a g e | 50

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.

---why interface and why abstract class?

----What is sealed class in C#?


Sealed class is used to prevent the class from being inherited from other classes.
So “sealed” modifier also can be used with methods to avoid the methods to
override in the child classes.

-----Difference between static and sealed classes?


Static class:
1) A static class cannot be instantiated.
2) A static class can have only static member (e.g static method, property,
and variables).
3) A static class restrict the user to call default constructor of the class.
4) Static classes can only have static constructor to initialize static members.
5) Static classes are sealed so they cannot be inherited.
Sealed Class:
1) When a class defined as sealed it’s not possible to inherit.
2) A Sealed class is last class of Inheritance feature.
3) Use the sealed modifier in a class declaration to prevent inheritance of the
class.
4) It is not permitted to use the abstract modifier with a sealed class.
5) Structs are implicitly sealed; therefore, they cannot be inherited.

---What is Generics in C#?


Generics in C# is used to makes the code typed independent and that way we can
reuse code with any type. When we use generic we get strongly type nature, and
performance also come from unnecessary from boxing and unboxing, we can
make generics to method, classes, interface and delegate.
Namespace – “System. Collections. Generic” is available in C# and this should be
used over “System. Collections” types.
P a g e | 51

-Generics introduce in C# 2.0.


-Generics allow you to write a class or method that can work with any data type.
-Har type k data type ko accept karta hai. Matlab kisi bhi type ka data type pass
karenge error nahi ayega.
-Versatile type k liye method hota hai.
-Code reusability k liye bahot benefit hai. Matlab ek hi function banyenge aur
deferent type k parameter ko pass kar sakte hai. Data type koi fix nahi hota hai.
Data type compile time par decide hoga.
-Hum run time par data type.
-Generic class ya method ko hum angle <> se define karte hai.
-Boxing or Unboxing ka koi concept nahi hota hai.
Generics allow you to define a class with placeholders for the type of its fields,
methods,
parameters, etc. Generics replace these placeholders with some specific type at
compile time.
We use <> brackets for this.
P a g e | 52

---What is generic collections?


Generic collection is strongly type and size are flexible. It has better performance
as compared to array list

----Explain the types of comments in C#?


Single Line Comment E.g. //
Multiline Comments E.g. /* */
XML Comments E.g.///

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

---Why we use delegates in c#?


Delegates are objects that contain information about the function rather than
P a g e | 54

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.

---Wheredo you use multicast delegates? This is a


very common interview question?
Multicast delegate makes implementation of observer design pattern very simple.
Observer pattern is also called as publish/subscribe pattern.

--- What is Event?


Events is nothing but rapper of delegate.
An event is something special that is going to happen. An event has a publisher,
subscriber, notification and a handler. An event is nothing but an encapsulated
delegate.

--Observer design pattern

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

---String Builder class in C#? StringBuilder


class represent the mutable string of characters and this class cannot be
inherited. It allows us to Insert, Remove, Append and Replace the characters.
“ToString ()” method can be used for the final string obtained from StringBuilder.
For example,
StringBuilder TestBuilder = new StringBuilder("Hello");
TestBuilder. Remove (2, 3); // result - "He"
TestBuilder. Insert (2, "lp"); // result - "Help"
TestBuilder. Replace ('l', 'a'); // result - "Heap"
P a g e | 55

---Partial Class in C#?


Partial classes concept added in .Net Framework 2.0 and it allows us to split the
business logic in multiple files with the same class name along with “partial”
keyword. Inheritance cannot be applied to partial classes.
Benefits
Basically solve the problem of separation of designer code and implementation
code. In Whidbey, partial classes are used to separate these ideas by having the
designer code in one file, and the user code in another.

---What is the difference between “dispose” and “finalize”


variables in C#? Dispose method uses interface – “IDisposable” interface which
free up both managed and unmanaged codes like – database connection, files etc.
Finalize method is used for garbage collection. So before destroying an object this
method is called as part of clean up activity.

---Why to use “finally” block in C#?


“Finally” block will be executed irrespective of exception. So while executing the
code in try block when exception is occurred, control is returned to catch block
and at last “finally” block will be executed. So closing connection to database /
releasing the file handlers can be kept in “finally” block.

---What is the difference between “finalize” and “finally”


methods in C#? Finalize – This method is used for garbage collection. So
before destroying an object this method is called as part of clean up activity.
Finally – method is used for executing the code irrespective of exception occurred
or not.

---What is the difference between “throw ex” and “throw”


methods in C#? “throw ex” will replace the stack trace of the exception with
stack trace info of re throw point.
“throw” will preserve the original stack trace info.

---Can we have only “try” block without “catch” block in


C#? Yes, we can have only try block without
catch block.
P a g e | 56

---List out two different types of errors in C#?


Compile Time Error
Run Time Error

---Do we get error while executing “finally” block in C#?


Yes. We may get error in finally block.

---Mention
the assembly name where System
namespace lies in C#? Assembly Name –
mscorlib.dll

---What are the differences between static, public and


void in C#?
-Static classes/methods/variables are accessible throughout the application
without creating instance. Compiler will store the method address as an entry
point.
-Public methods or variables are accessible throughout the application.
-Void is used for the methods to indicate it will not return any value.

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

---Explain Jagged Arrays in C#?


If the elements of an array is an array then it’s called as jagged array. The
elements can be of different sizes and dimensions.

---Can we use “this” inside a static method in C#?


No. We can’t use “this” in static method.
P a g e | 57

---What are value types in C#?


decimal, int, byte, enum, double, long, float

---What are reference types in C#?


class, string, interface, object

---Can we override private virtual method in C#?


No. We can’t override private virtual methods as it is not accessible outside the
class.
---Intry block if we add return statement whether
finally block is executed in C#?
Yes. Finally, block will still be executed in presence of return statement in try
block.

---What you mean by inner exception in C#?


Inner exception is a property of exception class which will give you a brief insight
of the exception i.e., parent exception and child exception details.

---Whatis the difference between methods –


“System.Array.Clone()” and
“System.Array.CopyTo()” in C#?
“CopyTo ()” method can be used to copy the elements of one array to other.
“Clone ()” method is used to create a new array to contain all the elements which
are in the original array.

---How we can sort the array elements in descending


order in C#? “Sort ()” method is used with “Reverse ()” to
sort the array in descending order.

---Explain circular reference in C#?


This is a situation where in, multiple resources are dependent on each other and
this causes a lock condition and this makes the resource to be unused.
P a g e | 58

---List out some of the exceptions in C#?


NullReferenceException- NullReferenceException is common. It indicates that you
are trying to access member fields, or function types, on an object reference that
points to null. It indicates a flaw in the code.Null.
ArgumentNullException- ArgumentNullException is thrown when a method is
invoked and at least one of the passed arguments is null but should never be null
DivideByZeroException- The exception that is thrown when there is an attempt to
divide an integral or decimal value by zero.
IndexOutOfRangeException- The exception that is thrown when an attempt is
made to access an element of an array with an index that is outside the bounds of
the array. This class cannot be inherited.
InvalidOperationException- The exception that is thrown when a method call is
invalid for the objects current state.
StackOverflowException- The exception that is thrown when the execution stack
overflows because it contains too many nested method calls. This class cannot be
inherited.
---Object pool in C#?
Object pool is used to track the objects which are being used in the code. So
object pool reduces the object creation overhead.

---Whatare the differences between events and


delegates in C#? Main difference between event and delegate
is event will provide one more of encapsulation over delegates. So when you are
using events destination will listen to it but delegates are naked, which works in
subscriber/destination model.

---Can we use delegates for asynchronous method


calls in C#? Yes. We can use delegates for asynchronous
method calls.

---What are the uses of delegates in C#?


Callback Mechanism
Asynchronous Processing
Abstract and Encapsulate method
Multicasting
P a g e | 59

---What is Nullable Types in C#?


Variable types do not hold null values so to hold the null values we have to use
nullable types. So nullable types can have values either null or other values as
well.
Eg: Int? mynullablevar = null;

---Why to use “Nullable Coalescing Operator” (??) in


C#? Nullable Coalescing Operator can be used with
reference types and nullable value types. So if the first operand of the expression
is null then the value of second operand is assigned to the variable.
For example,

double? myFirstno = null;


double mySecno;
mySecno = myFirstno ?? 10.11;

---What is the difference between “as” and “is” operators


in C#? “as” operator is used for casting object to type or
class. “is” operator is used for checking
the object with type and this will return a Boolean value.
---Define Multicast Delegate in C#?
A delegate with multiple handlers are called as multicast delegate. The example
to demonstrate the same
is given below
public delegate void CalculateMyNumbers(int x, int y);
int x = 6;1
int y = 7;
CalculateMyNumbers addMyNumbers = new
CalculateMyNumbers(FuncForAddingNumbers);
CalculateMyNumbers multiplyMyNumbers = new
CalculateMyNumbers(FuncForMultiplyingNumbers);
CalculateMyNumbers multiCast = (CalculateMyNumbers)Delegate.Combine
(addMyNumbers, multiplyMyNumbers);
multiCast.Invoke(a,b);
P a g e | 60

---What is the difference between CType and Directcast in


C#? CType is used for conversion between type and the
expression. Directcast is used for converting the
object type which requires run time type to be the same as specified type

---Is C# code is unmanaged or managed code?


C# code is managed code because the compiler – CLR will compile the code to
Intermediate Language.

---What is meant by managed and unmanaged code


in net?
Managed code is the code which is managed by the CLR (Common Language
Runtime) or we can say run under the CLR in .NET Framework. Whereas the
Unmanaged code is the code which is directly executed by the operating system
or don’t run under CLR called Unmanaged code. Like c++ code, Vc++ or vb6 code.

---Why to use lock statement in C#?


Lock will make sure one thread will not intercept the other thread which is
running the part of code. So lock statement will make the thread wait, block till
the object is being released.

---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");

---How to check whether hash table contains specific


key in C#? Method – “ContainsKey” can be used to
check the key in hash table. Below is
the sample code for the same –Eg: myHashtbl.ContainsKey("1");
P a g e | 61

---Whatis the difference between “continue” and


“break” statements in C#?
“continue” statement is used to pass the control to next iteration. This statement
can be used with – “while”, “for”, “foreach” loops.
“break” statement is used to exit the loop.

---Write a sample code to write the contents to text


file in C#? Below is the sample code to write the
contents to text file –Using System.IO;
File.WriteAllText(”mytextfilePath”, “MyTestContent”);

---What does the term immutable mean?


The data value may not be changed. Note: The variable value may be changed,
but the original immutable data value was discarded and a new data value was
created in memory.

---What is difference between classes and structures?


-A struct is a value type and a class is a reference type.
-There is no encapsulation in struct but in class it has.
-Classes support inheritance. No inheritance for structs.
-Struct does not support oops concept. classes support all oops concept
-In struct there is no scope like private and public.
-We use struct mainly for data structure. Single link list, Double link list and
circular link list. And class for application programming architecture.
-Classes are stored on heap and struct are stored on stack.
-Classes can have explicit parameter less constructors. But structs doesn’t have
this.
-A struct cannot inherit from another struct or class, and it cannot be the base of
a class. Like classes, structures can implement interfaces.
-Struct to kewal data structure k liye bana hai. Data programing interface k liye
nahi bana hai. jo bhi variable struct me hote hai by default public hote 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 matlab reference
type use karne se hume 2 block milta hai ek statck aur ek heap.
P a g e | 62

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

---What is garbage collection / Collector?


This is the main and important feature provided by CLR is garbage collection.
When we develop any application memory is main concern. The purpose of GC is
auto memory management. We can clear memory two ways manually and
automatically.
GC provide automatically memory management. There are several feature
provided by GC

Garbage collection is a mechanism that allows the computer to detect when an


object can no longer be accessed. It then automatically releases the memory used
P a g e | 64

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.

Automatic memory management is made possible by Garbage Collection in .NET


GC always worked on managed heap. When a class object is created at runtime,
certain
memory space is allocated to it in the heap memory.
If the system has low physical memory, then garbage collection is necessary.
If the GC. Collect method is called, then garbage collection occurs. However, this
method is only
called under unusual situations as normally garbage collector runs automatically.
With using objects gets automatically disposed

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?

---What is nested class?


A Nested class are classes within classes.

---Difference Between String and StringBuilder


String Class
Once the string object is created, its length and content cannot be modified.
Slower
StringBuilder
P a g e | 65

Even after object is created, it can be able to modify length and content.
Faster

---Why C# is called Strongly Typed Language?


C# is called Strongly Typed Language because its type rules are very strict. For
example, you can't have called a function that is designed to call Integer with a
string or decimal. If you want to do so then you will have to explicitly convert
them to integer.

----When Does Garbage Collector runs?


1. When the system has low physical memory
2. Acceptable memory heap is increased.
3. GC. Collect method is called.

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

----Whatis the use of virtual, sealed, override, and


abstract?
• The use of virtual keyword is to enable or to allow a class to be overridden in
the derived class.
• The use of sealed keyword is to prevent the class from overridden i.e. you can’t
inherit sealed classes.
• The use of override keyword is to override the virtual method in the derived
class.
• The use of abstract keyword is to modify the class, method, and property
declaration. You cannot directly make calls to an abstract method and you cannot
instantiate an abstract 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

Instance read only variable.


When we declare a class, class would be several variables. This is the object level
variable. The value of the variable should not be change by the object.it initialize
only one time.it only initialize by the instance constructor. Is save in heap
memory.

Static variable.
Static read only variable.
Constant variable.

--Whatis the difference between


System.Console.Writeline and
System.Console.Write?
Both WriteLine () and Write () functions enable you to print information on the
console in the same manner.
System.console.WriteLine() prints the information on screen and goes to next
line .However, System.console.Write()print the information on the screen ,but
does not go to next line.
---What is the difference between Var and Dynamic?
We can save or store any kind of data type in both key word. Both are used for
defining the aliasing name of any type.
-Var
It checked or decide data type at compile time.
While using var we get intelligence of datatype.
Errors are caught at compile time.
P a g e | 68

Declaring and initializing both same time must.


Hum jaisa variable type declare karte hai waisa hi var ban jata h.
Value cannot be change letter in the code.
We cannot change the variable data type later in the code.
Var makes alias and follow early binding.

-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

Dynamic obj = new employee


Agar hum obj dot lagate hai to hume kuch bhi dikhai nahi dega. We cant acces any
aliment of the class even public function as well. Q k dynamic type me data type
run time par decide hota hai.

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.

----Difference between Static Variable, Constant, Read-only


in c#?

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.

---Difference between Value types and Reference


types?
Value Types
Value Types cannot inherit from another class or struct. Value types can only
inherit from interfaces
Value types are stored on the stack
Value type variables directly contain their values
In value type only single thread. executing function.

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

---What is the difference between EXE and DLL?


There are two types of assembly DLL and EXE.
An EXE file can be run independently while a DLL is used by other applications
A DLL file can be reused by other applications while an EXE cannot
A DLL would share the same process and memory space of the calling application
while an EXE creates its separate process and memory space
-DLL-Dynamic Link Library
DLL is a library that contains code and data that can be used by more than on
program at the same time.
assembly is a precompiled .net code which can be run by the CLR.
-EXE

---Can class exists without namespace?


Yes, it would be under global namespace.
---What is the difference between web.config and
Machine.config?
-web.config
It is an xml document which embedded in the web app.it contain information
about control module loading, session, state configuration, app language, security
configuration, compilation setting, database connection and much more.
-Machine.config
It is an xml document which contain global settings for Machine. This file located
in
C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
--What is the difference between Yield and Return?
-Yield if you want to custom iteration and state full iteration.
The only difference between yield and return is whenever yield statement is
encountered in a function, the execution of function is suspended and a value is
send back to the caller but because of yield whenever the function is called again,
the execution of function begins where it left off previously. When resumed, the
function continues execution immediately after the last yield run. Thus yield
allows a function to produce a series of values over time. The only requirement
for yield return statement is that the function containing yield should return an
IEnumerable and no matter from where that function is called it should be called
from an iteration block i.e. foreach statement.
P a g e | 71

---Canwe create default and parameterize


constructor in Abstract class?
Yes, we can create default and parametrized constructor in abstract class. we can
call abstract class constructor via derived class using constructor chaining.

---What is extension method?


This is the new feature added in c#3.0,
Extension method allows developers to extend functionality of an existing type
without creating a new derived type, recompiling, or otherwise modifying the
original type. C# extension method is a special kind of static method that is called
as if it was an instance method on the extended type. In this article, we will create
a class library and we will then extend its functionality from the caller code by
implementing extension methods in C#.

---Anonymous type or method?


An Anonymous method is a method without a name. Anonymous methods in C#
can be defined using the delegate keyword and can be assigned to a variable of
delegate type.
public delegate void Print(int value);

static void Main(string[] args)


{
Print print = delegate(int val) {
Console.WriteLine("Inside Anonymous method. Value: {0}", val);
};
print(100);
}
---What is Thread?
Thread is a light weight process. A process has at least one thread which is
commonly called as
main thread which actually executes the application code. A single process can
have multiple
threads.

---What is Thread Life cycle?


P a g e | 72

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 Thread Pool?


Thread Pool is a collection of thread used to perform no of task in background.
Once thread completed is task then it goes back to the pool of waiting thread
queue instead of garbage collector. Which makes the things faster.
System.Threading namespace we need to call thread pool class, using thread pool
object we need to call method i.e. "QueueUserWorkItem" - which Queues
function for an execution and a function executes when a thread becomes
available from thread pool.
The default size of the thread pool for a process depends on several factors, such
as the size of
the virtual address space.

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

What is 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.
Loosely Couple and Tight Couple
Tight Coupling is when in a group, classes are highly dependent on one another.
P a g e | 73

Loose Coupling is achieved by means of a design that promotes single-


responsibility and separation of concerns.

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.

Loosely Couple and Tight Couple


Tight Coupling is when in a group, classes are highly dependent on one another.
Loose Coupling is achieved by means of a design that promotes single-
responsibility and separation of concerns.

Why is the Main() method use in C# static?


A main method is static because it is available to run when your program starts
and as it is the entry point of the program it runs without creating an instance of
the class.

What is indexing in c#?


Indexers are a syntactic convenience that enable you to create a class, struct, or
interface that client applications can access as an array.

How to implement two interface with same method in


C#? If we have two interface with same method name, then
a class need to implement interface explicitly in a program. We implement the
interface explicitly in a class, using interface name e.g.
“interfacename.method()”Also note that when we use explicit interface
implementations, the functions are not public in the class.
P a g e | 74

Output:
Bank Customer …
Loan Customer …

When a method is explicitly implemented in a class in C#, it cannot be accessed


through a class instance if you use class reference, but only through an interface
reference pointing to the class instance. For example,
P a g e | 75

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.

What is the use of JIT(Just in time compiler)?


P a g e | 76

Does .NET support multiple language?


it supports many other languages. like C#,vb.net , f# Vb++ , C++. Does not matter
what language you are using finally it will be in convert into IL code.
What is CLR (Common language Runtime)?
It run time execution environment for .net. so CLR is responsible for executing
your application. CLR convert you IL code into machine language. this is the first
work of CLR. CLR also responsible for executing garbage collector.
IEnumerable vs IQueryable c#?
Both are interface to .net collection. IQueryable interface inherit from
IEnumerable interface. Whatever things IEnumerable can do same things
IQueryable also can do. But something IQueryable can do but IEnumerable can’t
do. Basically
these are used for querying data from database. If you talking about IEnumerable
it brings data from database on the server side, load data in-memory on a client
side and then filter data. If you talking about IQueryable it brings data from data
base on the server side with all filters. IEnumerable extension methods take
functional object. It’s all about where filter gets executed.
So IEnumerable filter get executed on client side and IQueryable filter get
executed in database. IQueryable is much faster than IEnumerable
What is string interpolation?
String interpolation first time introduced with C# V6 and letter. Its formatted
string by inserting variables values. Less line of code can be achieving in single
line.
Basically we can format the string as their own arguments instead of referring to
the placeholder. We need to use $ symbol before starting the string. Instead of
using placeholder we can pass directly string.
P a g e | 77

Difference between string and String in c#?


Does not matter what you are using both are same. Both derived from
System.String class. string is an alias for String and nothing else.
What is reflection in c# ?

Abstraction vs Encapsulation
P a g e | 78

You might also like