C# interview ques ons
Part 1-Ques ons on Stack, Heap, Boxing,
Unboxing, Array, ArrayList, Generics,
Threading.
1. Difference between .Net and C#?
C# is a programming language, it has a syntax’s, it has a
seman cs, it has a grammar, it has a source code while
.net framework is a collec on of libraries as well as it
helps to run your .net applica on or C# applica on and
using both of them we will create an applica on.
You will use C# and you will invoke the .net framework
libraries, and .net will also has a thing called as CLR to
make your applica on running.
2. What is IL (Intermediate Language) code? And what is
the use of JIT?
IL code is a par ally compiled code
JIT (Just in Time) compiled IL code to Machine language.
3. Is it possible to see this IL code visually?
Yes, it is possible to see this IL code visually by using
Disassemblers like ILDSM or ILSpy
For example, in my computer I have a compile code
which is a DLL (Dynamic Link Library) to see this I will run
ILDSM which is a Disassembler which comes with the
visual studio command prompt and we can see IL code
there.
4. What is the benefit of compiling in to IL code?
The run me environment and development
environment can be very different. So depending on the
run me environment JIT compiles the best op mized
code as per that environment.
5. Does .net support mul ple programming languages?
Yes, like VB.NET, C#, F#, either you work with any
programming language at the end it will get compiled to
IL code.
The whole point of crea ng this mul ple programming
kind of environment for developers is that some
developers like C# bcz it is case sensi ve, it has a curly
bracket’s but if you’re a developer who started career in
visual basic 4 and visual basic 6 go with VB.NET
6. Explain the importance of CLR?
Common Language Run me, it helps to execute your
.net applica on
It has two primary goals:
CLR invokes JIT to compile to IL code. i.e., It
converts IL to Machine level lang
Cleans any unused objects by using GC. (it runs
your applica on a er conver ng into MLL and
when your applica on runs if there is any kind of
unused objects memory that is claimed by the gc).
7. What is managed and unmanaged code?
Code that executes under the environment of CLR is
called as a manager code. (all c#, F#...code)
C++, C codes come under unmanaged code. Unmanaged
codes have their own environment in which the code
runs and it’s completely outside the control of CLR.
8. What is GC?
GC is a back ground process which cleans unused
managed resources.
9. Can garbage collector claim unmanaged objects?
No, it cannot collect objects which are created outside
CLR run me.
10. What is the importance of CTS?
Common Type System, CTS ensures that data types
defined two different languages gets compiled to a
common data type.
Suppose, I want to use VB.NET code inside C# both
having two different data types so both compiled to
common type system which is int 32, same for other
data types.
11. Explain CLS?
Common Language Specifica on
Set of rules for wri ng code that ensures compa bility
between different .NET languages (C#, VB.NET, F#, etc.).
Purpose: Allows code wri en in one .NET language to be
used in another language without issues.
Key Points:
Ensures cross-language compa bility in .NET.
Defines common rules for all .NET languages.
No use of features like unsigned data types that aren’t
supported by all languages.
Simple Example:
C# lo public method lo capital le ers use cheyyachu.
But oka .NET language like VB.NET lo, case-sensi ve
kaadu.
So, CLS antaadi:
"Use only common features that all languages
understand."
12. What is boxing and unboxing?
When value type is moved to a reference type -> boxing
and vice versa is termed as unboxing.
Int I = 10;
Object y = I; // boxing value type to a reference
Int z = (int)y; // unboxing ref value
13. What is the consequence of boxing and unboxing?
Its performance.
Bcz, your jumping from stack to heap and heap to stack
it leads to performance implica on.
14. Explain cas ng, implicit cas ng and explicit cas ng?
Cas ng: conver ng from one data type to another data
type
Implicit: when you are moving from lower data type to
higher datatype
Explicit: when you move from higher data type to from
lower datatype
15. Array and arraylist?
Array is fixed size, homogenous , performance high
Arraylist has not fixed size it is flexible, it is not strongly
typed (heterogenous), performance is low bcz of boxing
and unboxing in arraylist we have different data like int,
string like that so it perform boxing and unboxing. Due
to this performance implica on occurs.
16. What are generic collec ons?
It is a strongly typed (homogenous) and flexible. It has
be er performance as compared to arraylist.
It combines the good things of array (strongly typed) and
good things of arraylist (flexible)
List<int> x = new List<int>();
x.Add(1);
x.Add(2);
You can add many number of data i.e flexible
You cant add other data apart from int ( strongly typed)
17. What is the difference b/w using a thread and using
a TPL(Task Parallel Library)?
Task u lizes your processors (hardware components) we
don’t have to write extra code for it while threads have a
cpu affinity.
Task provides parallel processing
Thread follows sequen al processing or me slice.
In case of task I can return a result and also it cancel
task, Async, Await.
In case of thread I can’t to get result from a thread I will
use delegates, events and so on.
18. What is use of OUT keyword or what is OUT?
If you want to return mul ple outputs from a func on/
method you will use OUT keyword.
Sta c void Main(string[]args){
Int add =0;
Int sub=0;
MyMaths(10, 10, out add, out sub)
Console.Read();
}
Sta c void MyMaths(int num1, int num2, out int add,
out int sub){
Add = num1+num2;
Add = num1-num2;
}
19. What is IEnumerable in C#?
The goal is to enable itera ons or to enable this fantas c
foreach loop over a collec on
Sta c void Main(string[]args)
{
Var arr = new ArrayList();
Var list = new List<string>();
foreach(var item in arr)
{
}
foreach(var item in list)
{
}
}
But we can iterate a foreach loop without excep city tell
ienumerable right?
Yes, but IEnumerable helps to iterate over a collec on
without knowing the actual type of collec on you have
at the back. So, it’s acts like an abstrac on.
IEnumerable acts like an iterable collec on abstrac on
over any type of collec on.
And also it is very useful if you want to pass a generic
collec on
Sta c void Main(string[]args)
{
Foreach(var item in Get())
{
// this foreach loop doesn’t know that it will get an
arraylist or list so that is the use of IEnumerable, it is an
abstrac on
}
Sort(new ArrayList());
Sort(new List<string>());
}
Sta c void Sort(iEnumerable data) // generic
collec on passing
{
}
Sta c IEnumerable Get()
{
If(DateTime.Now.DayOfWeek==DayOfWeek.Monday)
{
Return new ArrayList();
}
Else{
Return new List<string>();
}
20. IEumerable, Yield, IQueryable, IEnumerator?
IEnumerable, IQueryable --- both are interfaces for .net
collec ons,
IEnumerable--- in memory collec ons
IQueryable---collec on connected to DB via EF or LINQ.
Yield keyword: helps to do custom stateful itera on over
a collec on
It is useful in two cases:
When you want to do custom itera on
When you want to do stateful itera on
21. Which design pa ern from Gang of Four(GOF) does
IEnumerable implement?
Iterable pa ern
22. Thread and Async Await?
Async methods are intended to be non-blocking
opera ons, it doesn't create new thread whereas Thread
creates new thread and runs at the same me
(concurrently) on different CPU core on the system.
23. Concurrent vs parallel?
Concurrency means execu ng mul ple task on the same
core, while parallelism means execu ng mul ple task on
mul ple core.
Part 2 - Ques ons on Delegates, Event & Delegates vs
Events.
19. What is delegates?
Delegate is a pointer to func on,
Class Program
{
Public delegate void SomeDelegate();
Public sta c SomeDelegate somedelobj = null;
Sta c void Main(string…args)
{
Somedelobj = Fun1();
Somedelobj.Invoke();
Fun1(); // can directly also call without invoking
}
Sta c void Fun1(){
Console.WriteLine(“hello”);
}
but it’s most important use is callbacks, when we talk
about callbacks we talk about parallel processing.
First thing we have a parallel processing and we want to
keep sending some messages from one thread to
another thread or from one process to another process
Asynchronous processing means one thread running in
one stack another thread running in another stack and
they are running parallely.
Class Program
{
Sta c void Main(string[]args)
{
SomeClass x = new SomeClass();
x.senderobj = Receiver;
Thread t = new Thread(new
ThreadStart(x.HugeProcess)); // huge process run on
some different
t.start();
// main thread
Console.WriteLine(“Program.cs”);
Console.ReadLine();
}
Sta c void Receiver(int i)
{
Console.WriteLine(i);
}
Class SomeClass
{
Public delegate void Sender(int i); // declara on of
delegates
Public Sender senderobj = null;
Public void HugeProcess()
{
For(int i=0; i<1000;i++)
{
Thread.Sleep(100);
Senderobj(i); // callback
}
Defini on: Delegate is a pointer to func on.
Thread, Parallel, Async processing prequiste for
delegates
Delegate is a callback and it is used for callbacks and
specifically when you have a parallel processing.
Ex: when you are searching a file in a folder so you have
a huge group you have a big group which keeps going
out there and from that you will see once you get a file
so if you ever seen your search of windows if you search
a file star.txt you will find that your main window is one
thread and there is a another thread which actually is
going and searching the file and every now and then he
is making a call back to the UI and displaying the file
name.
Thread, parallel -> delegates -> mul cast -> Event
Mul cast delegate:
We had a very simple callback that must be like one to
one sender one receiver but if you want to convert it to
a mul cast you can just keep plus equals. +=
Or if you want to unsubscribe -=
x.senderobj + = Receiver;
x.senderobj += Receiver1;
x.senderobj += Receiver2;
Sta c void Receiver(int i)
{
Console.WriteLine(i);
}
Sta c void Receiver1(int i)
{
Sta c void Receiver2(int i)
{
Console.WriteLine(i);
}
Mul cast delegates vs publisher, subscriber
The problem of naked delegates:
In mul cast we can keep x.senderobj = null bcz the Main
thread is controlling he has a power to keep if we keep it
null no receiver will get any message.
In publisher, subscriber it is not the case, if we watching
a new channel he is talking con nusly but we can’t go
and slap him we can just unsubscribe or off t.v that’s it.
So broadcas ng means we can manipulate each other.
If you want to make it pure publisher, subscriber make it
event. Public event Sender senderobj = null;
Events uses delegates, events encapsulates delegates, it
changes that mul cas ng that broadcas ng into a
publisher, subscriber mechanism.
x.sender += receiver;
x.sender +=receiver1;
x.sender +=receiver2;
// x.sender = null -> it is not possible can’t manipulate
bcz above it says it can subscribe.
From Broadcas ng to publisher subscriber – Events
(observer design pa ern)
Observer means he can subscribe it he can unsubscribe
it but he cannot destroy it by keeping null.
Means,, in radio u can on the bu on u can off the bu on
but you cannot go to the radio sta on and do
something, bcz it is not in our control.
Ex: youtube subscriber (you can go subscribe and
unsubscribe but you cannot go to the admin(publisher)
and make it subcribes as null).
Ex: signal
Event: it is a encapsula on over delegates, it is a pure
publisher subscriber mechanism.
NOTES:
Delegate is a pointer to a func on and very useful as
callbacks to communicate between threads.
Delegate is meant for callbacks
Delegates can be converted to mul cast by keeping += -=
In mul cast delegate client can manipulate the senders
delegate objects
In mul cast delegate the delegates is naked.
Event is pure publisher subscriber model
Event is a encapsula on over delegates
Part 3 - Ques ons OOP, Abstrac on, Encapsula on,
Inheritance, Virtual, Overriding and overloading.
1. Why do we need OOP?
Object oriented programming lang helps us to think
in terms of real-world objects.
Ex: Suppose you want create a so ware for hospital
Class Program
{
Sta c void Main(string[]args)
{
}
}
Class Pa ent
{
Public string name{ get; set;}
Public string address{get; set;}
Public doctor doctorwhowilltreat {get; set;} // here
doctor object crea on
}
Class doctor
{
Public string name {get; set;}
}
}
The code is mimicking the real-world object.
Pa ent has a name, address, there is a doctor who
is allocated to pa ent, by having this approach you
can manage your code be er, your gets organized
properly. So object oriented programming helps us
to think in terms of real-world objects.
2. What are the important pillars in OOP?
Abstrac on: Show only what is necessary
Polymorphism: Object acts differently under
different condi ons.
Ex: user object can become an employee or
become an admin or worker.
Inheritance: Parent child rela onship, where you
have something common in the parent and the
child can inherit and adds something more in it.
Encapsula on: Hide complexity
3. What is a class and object?
Class is a type, blue print and (to use the class we
need to create the instance of the class which is
object) object is an instance of the class.
Class Program
{
Sta c void Main(string[]args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
E 1.name = “shiv”;
E2. Name = “raju”;
CW(“Hello World!”);
}
}
Public class Employee
{
Public string name {get; set;}
Public string address {get; set;}
}
4. Difference b/w Abstrac on and Encapsula on?
Public class Employee
{
Public string name {get; set;}
Public string address {get; set;}
Public void Validate()
{
CheckName();
CheckAddress();
}
Private void CheckName()
{
}
Private void CheckAddress()
{
}
}
In code we are showing only validate method and
not showing checkname, checkaddress.
Notes:
Abstrac on happens during design phase, What has
to be shown public
During execu on phase developer uses
encapsula on to implement (the thought process)
of abstrac on
Encapsula on implements abstrac on.
Encapsula on and abstrac on complements
eachother.
5. Explain inheritance?
It is one of proper es of object oriented
programming where in you can define a parent and
child rela onship between two classes.
What is is-a rela onship?
Is-a rela onship is again a parent child rela onship,
ex: manager is a child of employee
6. Explain virtual keyword?
7. What is overriding?
Virtual keyword helps us to define some logic in the
parent class which can be overridden in the child
class.
Public class Employee
{
Public string name {get; set;}
Public string address {get; set;}
Public virtual void Validate()
{
CheckName();
CheckAddress();
}
Public class Manager : Employee
{
Public void Management()
{
}
Public override void validate()
{
// our own logic.
}
}
So, virtual keyword helps us to provide some
implementa on in the parent class which can be
overridden in the child class--- this concept is also
termed as overriding.
8. What is overloading?
Same method names with different signatures in
the same class.
9. Overloading vs overriding?
Overloading: Same method names with different
signatures in the same class
Overriding: using virtual keyword and overriding in
child class.
It comes in a parent-child rela onship so there
should be a parent child rela onship or else
method overriding does not exists.
Part 4 - Ques ons Polymorphism, Sta c vs Dynamic
polymorphism and operator overloading.
10. What is polymorphism?
Poly= many
Morphism=change as per situa on
It is an ability of object to act differently under
different condi on.
Class Program
{
Sta c void Main(string[] args)
{
Employee e = new Manager(); // here it is acts like
a manager and in below it ac ng like a supervisor.
e = new Supervisor();
}
}
Public class Employee{}
Public class Manager : Employee{}
Public class Supervisor : Employee{}
}
11. Can polymorphism work without inheritance?
No, to implement a polymorphism inheritance is
must.
12.Sta c vs Dynamic polymorphism?
Sta c polymorphism is implemented by method
overloading.
Dynamic polymorphism is implemented by method
overriding.
13. Explain operator overloading?
It is a concept of polymorphism where we can
redefine operators like +, -,* sign with addi onal
func onali es
The ability to overload an opera on with
func onali es and to do custom operator
overloading then use the operator keyword.
Var x = “raju” + “ramu” concatena on
If we change addi on
Var x = 1 + 2 - addi on performing
By default, you will see polymorphism in .net
14. What if we want to go and implement your own
logic of polymorphism or do a custom operator
overloading?
Sta c void Main(string[]args)
{
Var x = 1+2;
Var o1 = new SomeClass(10); // crea ng own
objects
Var o2 = new SomeClass(20);
Var o3 = o1+o2;
}
Public class SomeClass
{
Private int someValue;
Public SomeClass(int val)
{
someValue = val;
}
Public sta c SomeClass operator + (SomeClass arg1,
SomeClass arg2)
{
Return new SomeClass(arg1.someValue +
arg2.someValue);
}
15. Why do we need Abstract classes?
It is a half defined parent class or a par ally defined
parent class. It has half defined and full defined
methods also.
Bcz it is half defined you cannot create instance of
that class.
16. Are abstract methods virtual?
Yes,,,
Public abstract decimal CalculateDiscount();
In child class we can override it just like virtual
performance.
So, abstract methods in abstract classes by default
virtual.
17. Can we create an instance of abstract classes?
No, it is half defined you cannot create instance of
that class.
18. Is it compulsory to implement abstract classes?
Yes, bcz it is half defined so you have to implement
them in child classes otherwise it throws error.
19. Why simple class cannot replace abstract classes?
A simple base class can not be defined in a pure half
way.
Means inside a normal class cannot make it as half
method, if you want to make half class write a abstract
keyword in normal class.
20. Explain Interface and Why do we need it?
Interface is a contract, it is a legal binding between the
developer who is crea ng the class and the consumer
who is using the class.
21. Can we write logic in Interface?
No, it has purly signatures.
22. Can we define methods as private in Interface?
No, By default public
Always public.. you cannot even go and write any access
modifiers.
22. To change Interface what's the best prac ce?
Explain Mul ple Inheritance in Interfaces ?
We can add extra method if we want, by crea ng a new
interface which is implements the Interface(old one).
In all the classes which is implemen ng a interface will
get that extra method.
Public interface ICustomer
{
String name {get; set;}
String address {get; set;}
Decimal calculateDiscount();
}
Public interface ICustomerWithInterest : ICustomer
{
Decimal CalculateIntersest();
}
Public abstract class Customer : ICustomer,
ICustomerWithInterest // Mul ple inheritance
{
Public string name {get; set;}
Public string address {get; set;}
Public abstract decimal CalculateDIscount();
Public decimal CalculateInterset()
{
Return 0;
}
Sta c void Main(string[] args)
{
ICustomer x = new GoldCustomer();
x.name = “sss”;
x.CalculateDiscount();
ICustomer x1 = new SilverCustomer();
X1.CalculateDiscount();
ICustomerWithInterset c = new SilverCustomer();
c.CalculateDiscount();
c.CalculateInterset();
}
We use mul ple inheritance when you want to change
the interface.
23. Explain Interface Seggrega on principle?
Means, you do not force the clients to use unnecessary
methods which is not supposed to use.
So, it says that you create different, different interfaces
and you do not force your client to use them the
methods which he is not interested in.
Defini on Interface: Interface is a contract, by having
contract we have be er control on impact analysis,
change management and breaking changes.
Mul ple inheritance helps to add new methods with out
affec ng the old interfaces.
24. Can we create instance of Interface? No
25. Can we do mul ple inheritance of Interface? yes
26. Can we do mul ple inheritance with abstract
classes? No
Part 5 - Tricky Ques ons around Abstract classes and
Interfaces.
2.Interfaces are implemented
Abstract classes are inherited
1.Interfaces are contract which leads to other benefits
like unwanted impact analysis.
Interfaces:
It is a contract
Planning abstrac on
Interface is implemented
Abstract class:
It is a half-defined parent class
Share common logic in child classes
Abstract class is inherited
Abstract class can become a interface but in complicated
scenarios(it doesn’t support mul ple inheritance) it can
be design mistake.
Abstract class with out anything half defined can be
ARCHITECTURE mistake.
Part 7 - Ques ons around constructors & in parent child
which constructor fires first.
1. In parent child rela onship which constructor fires
first?
In a parent-child rela onship if you have constructor in
the parent and the child logically the parent constructor
should fire first and that is what exactly happens.
First the parent has to get instan ated and on that base,
the child has to get instan ated.
2. What about the ini alizers?
Child ini alizers run first
Parent ini alizers run second
3. flow:
Child ini alizers
|
Parent ini alizers
|
Parent constructors
|
Child Constructors
4. Why are ini alizer not following logic?
That's simply because the ini alisers run before the
base constructor, so the object isn't ready to be used
yet.
What if the parent tries to call to the child objects and
what if those objects are read-only?
Part 8 - Ques ons around Shadowing, Sealed, Nested
classes and par al classes.
Part 9 - Ques ons Around SOLID principles , Dependency
injec on (DI) and IOC
SOLID:
S: Single Responsibility principle(SRP)- one class should
do only one thing at a me
Public class Employee{
Int id; string name; int type; doTask(){ }
}
Public class SalaryCalcula on{
Public double CalculateSalary(Employee e){
Return 0; }
Before the CalculateSalary method(work) inside the
Employee class but calcula on of salary is not the work
of employee class, so we created a extra class and
passing parameter as employee so that separate class
will create the salary of employee.
One class should do only one thing and if it is doing
mul ple thing you need to break that class.
O- OCP(Open closed principle)- rather than modifying
class itself try to see that you can extend it.
(Or) the class should be opened for extension and it
should be closed for modifica on
Public class SalaryCalcula on{
Public double CalculateSalary(Employee e){
If(e.type==1){
Return 20000;
}
Else if(e.type==2){
Return 10000;
}
Else{
Return 0;
}}
Here we modifying class, based on
type(employee/manager/worker)
Instead above code this:
Public class SalaryCalcula on{
Public double CalculateSalary(Employee e){
Return 0;
}
Public class SalaryManagerCalcula on :
SalaryCalcula on{
Public override double CalculateSalary(Employee e){
Return 2000;
}
}
So, it says that you don’t have to change the exis ng
code bcz that code can have lot of references out there
and with that there will be a huge impact analysis and
you create new classes and whichever new clients want
to use this new classes they should be happy with this
new class and the old clients don’t get disturbed.
L - LSP(Liskov Subs tu on principle) – The child classs
should be able to implement all the method of the
parent class seamlessly and smoothly.
Liskov happens bcz requirements is misunderstood.
To fix liskov issue: abstrac on needs to be corrected.
They should inherit from different parent class.
Ex: We have a internal employee and contract employee
Internal employee have the all details and it contains
medicalinsurance also but contract employee doesn’t
have medicalemployee
So, create a baseEmployee class keep details all except
medicalinsurance.
In internalEmployee create separate class
healthinsurance. And make extends from baseEMployee
For contractemployee: baseEmployee, since
baseemployee doesn’t have medicalinsurance class it
doesn’t have.
So… they look like an employee, they work like an
employee but they do not have insurance
Like they look like a duck they quacks like a duck but it
has ba eries.
I – ISP(Interface Segrega on principle) – client should
not be forced to use methods which it does not need.
So, split the interface you segregate the interfaces
depending on what the client needs
D-Dependency inversion (DI) – Higher level module
should not depend on lower level module directly but
should (talk to an abstrac on like an interface )access it
via interface.
HomeController – higher level module
Contract, internal employees --- lower level module
The problem is ght coupling bcz homecontroller inside
that we have internalemployees class.
Suppose in future if we want to change
manageremployee instead of internalemployee we need
to chamge many things.
So create a separate interface IEmployee and make
internalemployees, contarctor employee extends that
interface.
And make Homecontroller access those internal
employees via interface.
Part 10 - Explain & Differen ate Composi on,
Aggrega on and Associa on in C#.
Inheritance: IS A
Using rela onship: HAS A
Three types of using rela onship:
1. Composi on:
PART-WHOLE vocabulary rela onship
Composi on and aggrega on have part whole
rela onship.
Sleeves is a part of shirt(whole)
Wheels is a part of car
Class Pa ent // whole
{
Public List<problem> problems { get; set;} // part
}
Composi on is a part-whole rela onship where both
part and whole object have same life me.
One can not stay with out each other. It is like a death
rela onship.
In a part whole rela onship when the part and the
whole objects are connected very ghtly then it
becomes a composi on rela onship they are composed
of each other.
2. Aggrega on:
Aggrega on is a part-whole rela onship where both part
and whole object can have different life me. They can
be allocated to some other objects, They can exist
independently.
Class Pa ent
{
Public List<problem> problems { get; set;}
Public Doctor Doctor{get; set;}
Public Pa ent (Doctor _doc){
Doctor = _doc;
Problems = new List<Problem>();
}
}
3. Associa on:
It says that there is a link between the objects.
Composi on and aggrega on are subset of associa on.
Associa on indicates there is dependency b/w objects.
Composi on and aggrega on are subset of associa on.
Rela onship b/w checkbed and pa ent is associa on.
Also pa ent to problem –associa on
Doctor to pa ent ---associa on.
Associa on : simple arrow
Aggrega on: Empty diamond
Composi on: Filled diamond
Part 11 - Crack ques ons on Stack, Heap, Boxing,
Unboxing, Value & reference types
1. Explain stack and Heap?
Stack and heap are memory types where applica on
running variables, object variables and object references
are stored.
2. Where are stack and heap stored?
Both stack and heap are stored in ram and not on a hard
disk.
3. What goes on stack and what goes on heap?
Primi ve datatypes and object references are stored on
Stack.
Actual object data and primi ve datatypes(depending
on implementa on-means if the primi ve data type is a
part of an object then it will go on a heap like obj.age =
100;) on heap.
Actual object data and also primi ve data type in case it
is a part of an instance.
4. How is the stack memory address arranged?
Stack(LIFO) memory address is con gious and memory
addresses do not have gaps.
5. How is stack memory deallocated LIFO or FIFO?
It is a stack memory and it goes with the LIFO style when
the memory is cleared. When the applica on stops
execu ng and it exits the way the memory is cleared it is
form the top.
6. How is memory and values stored primi ve and ref?
Value is stored wherever the memory addresses
Sta c void Main(string[]args)
{
Int yint;
Test obj;
Bool xbool;
Yint = 100;
Obj = new Test();
Obj.Name = “Shiv”;
Obj.Age =100;
Xbool = true;
}
In a stack primi ve datatypes memory address points to
the actual value.
&xbool---- x000003e404(address)
*&xbool true(actual value)
&yint -------x000003e418
*&yint 100
In object its memory address points to an other memory
address points and that memory address towards the
actual object data.
&xobj ----- x000003e408
*&obj x0000000000
7. Can primi ve data types be stored in heap?
Yes, if primi ve data types are part of an object then it
will go on heap.
8. Explain value types and reference types?
Value types are primi ve datatypes while reference
types are objects.
Int yint = 100;
Test obj = new Test();
Obj.Name = “Shiv”;
Obj.Age = 100;
Int zint = yintl
Test obj1;
Obj1 = obj;
}
9. What is byval and byref?
In byval/copybyvalue values are copied and fresh
memory address is allocated.
While in case of byref/copy byref they point to same
memory address and so the same reference.
10. Differen ate on copy by value and copy by ref?
One is copied by value and another one is copied by the
memory address that is the reference.
11. What is boxing and unboxing?
It is a process which happens when your variable jumps
from a stack to a heap and from a heap to a stack.
Boxing: When the variable jumps from a stack to a heap
it termed as boxing.
Int I = 100;
Object obj = I;
Unboxing: when the variable jumps from a heap to a
stack.
Int z = Convert.ToInt32(obj);
12. Is boxing unboxing good or bad?
No. It is a bad prac ce as it decreases performance. So
should be avoided as far as possible
While jumping from stack to heap or heap to stack it’s
actually copying and conver ng.
13. Can we avoid boxing and unboxing?
Boxing and unboxing can not be avoided completely.
Situa ons like taking data from UI or binding to grid will
have to go through boxing and unboxing. But
unnecessarily doing boxing and unboxing is a very bad
prac ce.
Int age = Convert.ToInt32(Console.Readline());
14. What effect does boxing and unboxing?
Boxing and unboxing decreases performance as data has
to be moved from stack to heap and heap to stack.
15. Are string allocated on stack or heap?
Strings are objects and they have reference on stack and
actual data is allocated on heap.
16. How many stacks and heaps are created for an
applica on?
One stack per thread and one heap for the whole
applica on.
Sta c void Main(string[]args)
{
Int I =10;
Test y = new Test();
y.name = “Shiv”;
y.age = 10; // un l here these will created in one
stack(main thread).
Thread t = new Thread(new Thread(new
ThreadStart(Func on1)); // from here it is allocated in
another stack( thread t).
t.start();
Console.Read();
}
Sta c void Func on1()
{
Int x = 10;
Test y1 = new Test();
Y1.name = “Shiv”;
Y1.age=10;
}
17. How are stack and heap memory deallocated?
Whatever memory is allocated either it is on a stack or
either it is on a heap it should be given back gracefully to
the OS. Otherwise it will leads to the memory leak and it
is not a good idea.
Stack memory are easy to deallocate, easy to allocate
while heap memories are it is easy to allocate but it is
tough to de-allocated and the heap memory gets
cleared by the garbage collector when objects having no
references, and stack memory gets cleared
automa cally bcz we know memory address is
con guous.
18. Who clears the heap memory? Garbage collector
19. Where is structure allocated stack or heap?
Structure is allocated on Stack
20. Are structures copy byval or copy byref?
Copy by val
21. Can structures get created on Heap?
Yes, structures can get created on heap if they are fields
of a class.
Struct MyStruct
{
Public int x;
Public int y;
}
Sta c void Main(string[]args)
{
MyStruct s1 = new MyStruct();
S1.x = 100;
S1.y = 200;
MyStruct s2 = s1;
Test s3 = new Test();
S3.struct1.x = 10;
S3.strut1.y =100;
Part 12 - What is Garbage collector, Managed vs
UnManaged code, Memory Leaks.
1. Explain Garbage collector (GC)?
It’s a background process which runs undetermis cally
and cleans unreferenced managed objects from
memory.
2. How does Garbage collector know when to clean the
objects?
When the objects goes out of scope GC reclaims the
memory and gives it to opera ng system.
3. Is it possible to check how this GC works? Is there a
way we can see this Heap memory?
Yes, we can analyze GC using performance counters.
Performance counters are counters or they are
measures of events in a so ware which allows us to do
analysis. These counters are installed when so ware is
installed.
4. Does Garbage collector clean primi ve types?
No, they are allocated on stack and stack removes them
as soon as the variables goes out of scope.
5. Managed vs UnManaged code/objects/resources?
Managed resources are those which are pure .net
objects and those objects are controller by .net clr.
Unmanaged resources are those which are not
controlled by .net clr run me like file handle, COM
objects, connec on objects and so on..
6. Can garbage collector clean unmanaged code?
No, GC only cleans managed objects.
Total memory of .net applica on = managed memory +
unmanaged memory.
7. Explain Genera ons?
Genera ons are logical buckets which have objects and
every bucket defines how much old the objects are.
8. What is GC0,GC1, and GC2?
GC0: short lived objects. Ex: local objects
GC1: Intermediate lived objects (Buffer)
GC2: Long lived objects. Ex: Sta c objects.
9. Why do we need genera ons?
The goal of genera ons is performance.
GC makes a assump on that if objects are needed
longer in memory then it should be visited less as
compared to objects which are freshly created and
which have high probability of going out of scope.
10. Which is the best place to clean unmanaged objects?
Destructor is the best place to clean unmanaged objects.
Class SomeClass
{
Public string SomeData{get; set;}
~SomeClass()
{
// clean up code for unmanaged
}
}
Constructor: constructor executes when object instance
is created.
Destructor: when object is going out of reference or
when it is cleaned up.
11. How does GC behave when we have a destructor?
When a class has a destructor GC takes more trips to
clean them and due that the objects are promoted to
upper genera on and thus pu ng more pressure on
memory.
Suppose, We have a unreferenced object and a ached
to that destructor there it refers unmanaged code.
When GC comes to collect unreferenced objects it first
cleaned up unmanaged code (file/..) and second me it
will clean up unreferenced objects.
So, due to the destructor in code, GC comes twice.
But in program we wrote a code to cleaned up
unmanaged code, so we tell the garbage collector first
itself that we cleaned up unmanaged code you don’t
worry and collect unreferenced objects only.
For that we use IDispose interface or IDispose
12. What do you think about empty destructor?
Having Empty destructor will cause lot of harm as
objects gets promoted to higher genera ons thus pu ng
pressure on the memory.
13. Explain Dispose pa ern?
In Dispose pa ern we implement “IDisposable” interface and
call “GC.SupressFinalize()” to tell the GC that the unmanaged
object has been cleaned up and claim the object do not wait.
Class SomeClass: IDisposable
{
Public string SomeData{get; set;}
~SomeClass()
{
// clean up code for unmanaged
}
Public void Dispose()
{
GC.SupressFinalize(this);
}}
14. Finalize vs destructor?
Finalize and destructor are the same.
Destructor calls the finalize method.
15. What is the use of using keyword?
Using statement defines a scope at the end of the scope
Dispose() is called automa cally.
For(double i=0; i<10000000;i++)
{
Using(SomeClass x = new SomeClass())
{
x.SomeData = DateTime.Now.ToString();
// x.Dispose();
}
}
Means, before this scope ends it will internally calls
dispose(), so use using keyword when u have
unmanaged code.
16. Can you force Garbage collector?
Yes, you can by calling “GC.Collect()”
17. Is it a good prac ce to force GC?
GC runs depending on various criteria’s like is memory
running low, is processor ge ng overloaded and it does
its work wonderfully.
Fiddling with GC is not recommended at all.
18. How can we detect a memory issues?
Memory issues can be detected by running tools like vs
code profiler, and we can check for two thigs:
If the memory is increasing linearly it’s a indica on of
memory issues, if the memory moving in a range it’s a
healthy sign
Also the memory alloca on and dealloca on should be
balanced if you just see memory alloca on and no
dealloca on is other sign that there is serious memory
problem.
19. How can we know the exact source of memory
issues?
In profiler we should check for the top most memory
allocated to objects.
Once we know the top most memory allocated to
objects we can then focus on code around those objects.
20. What is a memory leak?
Memory leak is a situa on where the memory
consumed by the applica on is not returned back to the
OS when the applica on exits.
21. Can .NET Applica on have memory leak as we have
GC?
Yes, its s ll possible to have memory leaks bcz GC only
takes care of managed memory.
If unmanaged memory is not claimed properly we cann
have memory leaks.
22. How to detect memory leaks in .NET applica ons?
Total memory of .net app = unmanaged +managed.
So if you see just see total memory is increasing and
managed is in a range then it means there is unmanaged
leak.
23. Explain weak and strong references?
Weak reference: It permits the GC to collect the object
but s ll allows to access the object un l GC collects the
object. We need to use “WeakReference” object to
create weak reference. In case for some reason if I need
it I would like to get it means we can referenced.
Strong reference: This is a normal referenced objects
and one object is marked for GC it can never be
referenced.
Class Program
{
Sta c WeakReference weak = new WeakReference(null);
Sta c List<SomeClass> mylist = new List<SomeClass>();
Sta c void Main(string[]args)
{
CW(“press enter to start”)’
Console.read();
Var obj1 = new SomeClass();
Var obj2 = new SomeClass();
weak.Target = obj2;
}
24. When will you use weak references?
Caching, object pooling. Wherever object crea on
process is resource intensive caching and pooling can
improve performance.