Sunday, June 16, 2019

Var and Dynamic in c#

What is difference Var and Dynamic in c#

Ans:

Many people have expressed confusion around the difference between var and dynamic in C#.  For both of them, the type is inferred rather than explicitly declared.

dynamic test = 1;
var test2 = 2;

If I hover my mouse over the “var” in the code above, IntelliSense will show me that the compiler has correctly inferred that it is an Int32.  If I hover over “dynamic”, it will continue to be typed as “dynamic” since dynamic types aren’t resolved until runtime.

However, var is statically typed, and dynamic is not.

// Can a dynamic change type?
dynamic test = 1;
test = "i'm a string now";  // compiles and runs just fine
var test2 = 2;
test2 = "i'm a string now"; // will give compile error
This is one of the key differences between dynamic and var.  A var is an implicitly typed variable that is inferred by the compiler, but it is just as strongly typed as if you had explicitly typed it yourself using “int test2 = 2;”.  A dynamic variable bypasses all compile-time type checking and resolves everything at runtime.

I’ll comment out the last line in the code above to get the code to compile, and add some code to verify the types of the variables.

// Can a dynamic change type?
dynamic test = 1;
Console.WriteLine("Dynamic as " + test.GetType() + ": " + test);
test = "i'm a string now";  // compiles and run just fine
Console.WriteLine("Dynamic as " + test.GetType() + ": " + test);
var test2 = 2;
//test2 = "i'm a string now"; // will give compile error
Console.WriteLine("Var as " + test2.GetType() + ": " + test2);

This produces the following output:

Dynamic as System.Int32: 1

Dynamic as System.String: i'm a string now

Var as System.Int32: 2








Question: Why we Used Dynamic ?

Ans:  It is  a new type that avoids compile time type checking.


A dynamic type escapes type checking at compile time; instead, it resolves type at run time.
A dynamic type can be defined using the dynamic keyword.


Difference between reflection and dynamic type.

ReflectionDynamic
Inspect (meta-data) Yes No 
Invoke public membersYesYes
Invoke private membersYesNo
CachingNoYes
Static class  Yes No

There are 4 great differences between Dynamic and reflection. Below is a detailed explanation of the same. Reference http://www.codeproject.com/Articles/593881/What-is-the-difference-between-Reflection-and-Dyna
Point 1. Inspect VS Invoke
Reflection can do two things one is it can inspect meta-data and second it also has the ability to invoke methods on runtime.While in Dynamic we can only invoke methods. So if i am creating software's like visual studio IDE then reflection is the way to go. If i just want dynamic invocation from the my c# code, dynamic is the best option.
DynamicVsReflection
Point 2. Private Vs Public Invoke
You can not invoke private methods using dynamic. In reflection its possible to invoke private methods.
Point 3. Caching
Dynamic uses reflection internally and it also adds caching benefits. So if you want to just invoke a object dynamically then Dynamic is the best as you get performance benefits.
Point 4. Static classes
Dynamic is instance specific: You don't have access to static members; you have to use Reflection in those scenarios.

Below are some differences between var and dynamic keyword in C#:

VarDynamic
It is introduced in C# 3.0.It is introduced in C# 4.0
The variables are declared using var keyword are statically typed.The variables are declared using dynamic keyword are dynamically typed.
The type of the variable is decided by the compiler at compile time.The type of the variable is decided by the compiler at run time.
The variable of this type should be initialized at the time of declaration. So that the compiler will decide the type of the variable according to the value it initialized.The variable of this type need not be initialized at the time of declaration. Because the compiler does not know the type of the variable at compile time.
If the variable does not initialized it throw an error.If the variable does not initialized it will not throw an error.
It support intelliSense in visual studio.It does not support intelliSense in visual studio
var myvalue = 10; // statement 1
myvalue = “GeeksforGeeks”; // statement 2
Here the compiler will throw an error because the compiler has already decided the type of the myvalue variable using statement 1 that is an integer type. When you try to assign a string to myvalue variable, then the compiler will give an error because it violating safety rule type.
dynamic myvalue = 10; // statement 1
myvalue = “GeeksforGeeks”; // statement 2
Here, the compiler will not throw an error though the type of the myvalue is an integer. When you assign a string to myvalue it recreates the type of the myvalue and accepts string without any error.
It cannot be used for properties or returning values from the function. It can only used as a local variable in function.It can be used for properties or returning values from the function.






Saturday, June 1, 2019

What is Garbage Collector

Ans:

When you create any object in C#, CLR (common language runtime) allocates memory for the object from heap. This process is repeated for each newly created object, but there is a limitation to everything, Memory is not un-limited and we need to clean some used space in order to make room for new objects, Here, the concept of garbage collection is introduced, Garbage collector manages allocation and reclaiming of memory. GC (Garbage collector) makes a trip to the heap and collects all objects that are no longer used by the application and then makes them free from memory.


Basically, heap is managed by different 'Generations', it stores and handles long-lived and short-lived objects, see the below generations of Heap:

0 Generation (Zero): This generation holds short-lived objects, e.g., Temporary objects. GC initiates garbage collection process frequently in this generation.

1 Generation (One): This generation is the buffer between short-lived and long-lived objects.

2 Generation (Two): This generation holds long-lived objects like a static and global variable, that needs to be persisted for a certain amount of time. Objects which are not collected in generation Zero, are then moved to generation 1, such objects are known as survivors, similarly objects which are not collected in generation One, are then moved to generation 2 and from there onwards objects remain in the same generation.


Managed objects are created, managed and under scope of CLR, pure .NET code managed by runtime, Anything that lies within .NET scope and under .NET framework classes such as string, int, bool variables are referred to as managed code.

UnManaged objects are created outside the control of .NET libraries and are not managed by CLR, example of such unmanaged code is COM objects, file streams, connection objects, Interop objects. (Basically, third party libraries that are referred in .NET code.)



Unmanaged Resource


When we create unmanaged objects, GC is unable to clear them and we need to release such objects explicitly when we finished using them. Mostly unmanaged objects are wrapped/hide around operating system resources like file streams, database connections, network related instances, handles to different classes, registries, pointers etc. GC is responsible to track the life time of all managed and unmanaged objects but still GC is not aware of releasing unmanaged resources
There are different ways to cleanup unmanaged resources:
  • Implement IDisposable interface and Dispose method
  • 'using' block is also used to clean unmanaged resources
There are couple of ways to implement Dispose method:
  • Implement Dispose using 'SafeHandle' Class (It is inbuilt abstract class which has 'CriticalFinalizerObject' and 'IDisposable' interface has been implemented)
  • Object.Finalize method to be override (This method is clean unmanaged resources used by particular object before it is destroyed)