Difference Between Var and Dynamic keywords & A small story. :)


Var Dynamic
1. The var keyword was introduced in .net 3.0 framework The Dynamic keyword was introduced in .net 4.0 framework
2. var is used to declare a variable, its data type is determined at the time of its declaration that means it is decided at compile time. Dynamic is also used to declare a variable, however its data type is not determined at the time of its declaration that means it is decided at run time.
3. You cannot change its type at run time. You can change its type at run time.
4. For e.g. if you declare a variable and assign a value(i.e. var variable1 = 1;)in that case compiler will considered it as integer and at run time if u change its value to string, an error will be thrown conversion from string to integer is failed. For e.g. if you declare a variable and assign a value (i.e. Dynamic variable1 = 1;) in that case compiler will not determine its type and run time you can change its value from string to integer.
5. The advantage of var :  if u assign any value from any  objects or variables to var, you will not have to decide its type explicitly, the compiler will set its data type based on assigned value and hence it useful for linq The advantage dynamic :  since value can be assigned at run time you can changes its data type by assigning value of type objects or variables at run time.
6. One more thing about var to remember is, var cannot be declared at class level and also it cannot be used as return type for any function. However dynamic can be declared at class level and also it can be used as return type for any function.
7.  Any invalid operation is caught at compile time.E.g. 

public class ClsStudent
Public void FunPubStd1()
var  ObjLocClsStudent = new ClsStudent();
ObjLocClsStudent. FunPubStd1()
ObjLocClsStudent. FunPubStd2()

In above mentioned example compiler will throw an error since it will not get function FunPubStd2 while compilation.

Any invalid operation is caught at run timeE.g. 

public class ClsStudent
Public void FunPubStd1()
var  ObjLocClsStudent = new ClsStudent();
ObjLocClsStudent. FunPubStd1()
ObjLocClsStudent. FunPubStd2()

In above mentioned example compiler will not throw an error since it will not check at run time.



Let’s take one real life example to differentiate between var and dynamic type and also use of one over another.

E.g. let’s imagine we are going to market to buy some vegetables and for that we are carrying a small polythene container however we get a call from home to bring 10 litters oil as well. Now problem arises here, how to carry 10 litters oil since we don’t have big tin container to carry a huge quantity of oil. You know why this problem raised because while leaving home we were asked to bring vegetables only so we carried only small polythene container and latter we were asked to bring oil only which is not possible to carry in small polythene container. So now just think if we would have such kind of container which is used to carry anything from small to large solid and liquid item well.

The same problem may arise in coding also as while compile time we might not know which types of data needs to be stored or carried So to overcome this problem we have dynamic type which can be used where compile time we don’t know the type of data we are going to get.  

By Sriramjithendra Posted in C#.NET

Division By Zero Doesn’t Always Raise An Exception

As the name itself suggests, this exception is raised at run time when the compiler tries to divide a number by zero. But this exception is not raised at all times. For instance, take the code below:

int num1 = 150;
int num2 = 0;
int result = num1/num2; 

The above piece of code, when executed will raise the DivideByZeroException.

But this is not the case when we divide a number of type double with zero. For instance, if you execute the code below, it will not raise any exception and will just execute normally.

double num1 = 15.8
int num2 = 0 
double result = num1/num2;  

Now, this is not a bug but in fact, a very normal scenario. The result of this division will be “Infinity”, positive infinity, to be precise. the double type has a property for infinity.


By Sriramjithendra Posted in C#.NET

What do we mean by immutable and mutable in OO?


Immutable: The state of the object cannot be changed after creation
Example: String , you can’t change it after it is created. It looks like you can, but what happens is that a new string is created.

Mutable: The state of the object can be changed after creation
Example: Stringbuilder , you can change this object after you have created it. You can append, remove, replace, or insert characters to the same object,- a new one isn’t created as with String.

By Sriramjithendra Posted in C#.NET

what is Lookup?

  • Dictionary and Lookup can be used as lookup structures, but there are some differences between the two.
  • Lookup has no public constructor and is immutable. Immutable means that we cannot add or remove items after creation.
  • Lookup can have duplicate keys
  • Lookup is created by the factory method ToLookup() found on classes that implement IEnumerable
  • Searching for a non-existing key will return an empty sequence instead of an exception
  • Another big difference is that Lookup maps to a collection of values, not a single value like Dictionary does.


Lookup lets you group items together by a key, but then access them via that key in an
efficient manner (rather than just iterating over them all, which is what GroupBy  lets you do).

One way to think about it is this: Lookup<TKey, TElement> is similar to
 Dictionary<TKey, Collection<TElement>>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

public class Test
    static void Main()
        // Just types covering some different assemblies
        Type[] sampleTypes = new[] { typeof(List<>), typeof(string), 
                                     typeof(Enumerable), typeof(XmlReader) };

        // All the types in those assemblies
        IEnumerable<Type> allTypes = sampleTypes.Select(t => t.Assembly)
                                               .SelectMany(a => a.GetTypes());

        // Grouped by namespace, but indexable
        ILookup<string, Type> lookup = allTypes.ToLookup(t => t.Namespace);

        foreach (Type type in lookup["System"])
            Console.WriteLine("{0}: {1}", 
                              type.FullName, type.Assembly.GetName().Name);

ToLookup returns a data structure that allows indexing.





By Sriramjithendra Posted in C#.NET

Disable All and Enable All the Foreign Key Constraint in Database

There are some scenarios (in  Testing environment) that we want to insert some data in a table  to test

-- Disable all the constraint in database

-- Enable all the constraint in database

Remember above script when executed right away enable or disable constraints
so be extremely careful to execute on production server.

Here is the Link.

Coding style.

First rule in coding is to make it work. Once you’ve done that, clean up your code
and make it neat, understandable and simpler if you can.

Cleaning up code is a good habit, but so is aiming for clean code in the first place.
You’ll still need to clean things up even if you plan ahead, but you won’t have quite
as much of a mess to start with.

The best coders and average coders usually have similar code, the difference is
how long it takes them to do it. If you take the time to plan ahead and solve the
problem before you start coding it will help you become one of the best coders.
Obviously you won’t be able to foresee every problem so you will have to make
the little things work and that can get pretty messy so what you are doing is called
refactoring the code (and this is a good practice). The best thing to do is first solve
the algorithm on paper and figure out how you are going to accomplish the task.
Then code it and get it to work, then refactor to clean up, make more readable
and optimize. Look at how long it is taking you to solve/code/debug and of those
three the debugging should take the least time, then coding a little more and solving
the problem the most time. Hope that helps out.

Why to use Entity Framework in .NET? Advantages of Entity Framework

Entity Framework is an Object Relational Mapping (ORM) Framework for the .NET Framework.
Entity Framework returns the data in your database as an object.
Entity Framework is actually written on top of ADO.NET, meaning under this framework,
we are still using ADO.NET. So we cannot say that Entity Framework is a replacement of ADO.NET.

Entity Framework basically generates business objects and entities according to the database tables.
Advantages of Entity Framework: There are lot of reason why should you use entity framework over LinqToSql and ADO.NET.
1. Database performance is improved. Updating your EDM based on your DB changes would take less time rather than the conventional methods. Database operations like select, insert, update, delete will work faster as you don’t have to hit database again and again as you would be working with objects not with database tables.
2. Entity Framework performing basic CRUD (Create, Read, Update, Delete) operations. So most of the time you don’t have to write any SQL yourself. When you make any changes to the object, the ORM will usually detect this, and mark the object as ‘modified’. When you save all the changes in your ORM to the database, the ORM will automatically generate insert/update/delete statements, based on what you did with the objects.
3. Entity Framework works on databases other than Microsoft SQL Server, like Oracle, MySQL etc. While Linq is limited to MS SQL Server. It is easy to add support for another database (like Oracle) as we are programming against a model.
4. Easily managing “1 to 1”, “1 to many”, and “many to many” relationships.
5. Ability to have inheritance relationships between entities.