Monday, 28 October 2013

Difference Between Var and Dynamic Keyword in C#

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




Object Dynamic Var
Can able to store any kind of value, because object is the base class of all type in .net framework. Can able to store any type of the variable, similar to old VB language variable. Can able to store any type of value but it require to initialize at the time of declaration.

Compiler has little information about the type

Compiler doesn't have any information about the this type of variable.

It's compiler safe i.e compiler has all information about the stored value, so that it doesn't cause any issue at run-time.

Object type can be passed as function argument and function also can return object type Dynamic type can be passed as function argument and function also can return object type Var type can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it defined.

Require to cast object variable to original type before using it. So this assigning to object type and converting to original type called as Boxing and Un-Boxing for value type and for the reference type its casting of types. It's actually increasing the overhead when we do this both operation.
Allows to perform operation of given type once it get cast any user defined or primitive data type.
Casting is not require but you need to know the property and methods related to stored type No need to cast because compiler has all information to perform operation.
Cause the problem at run time if the stored value is not get converted to underlying data type.

Cause problem if the wrong method or property accessed because all the information about stored value is get resolve only at run time

Doesn't cause problem because compiler has all info about stored value.
Useful when doesn't have more information about the data type. Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code. Useful when getting result out of the linq queries. In 3.5 framework it introduce to support linq feature.

Difference Between Encapsulation and Abstraction

What is encapsulation?

Encapsulation is the process of hiding irrelevant data from the user. To understand encapsulation, consider an example of mobile phone. Whenever you buy a mobile, you don’t see how circuit board works. You are also not interested to know how digital signal converts into analog signal and vice versa. These are the irrelevant information for the mobile user, that’s why it is encapsulated inside a cabinet.
In C# programming, we will do same thing. We will create a cabinet and keep all the irrelevant information in it that will be unavailable for the user.

Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation.

What is abstraction?

Abstraction is just opposite of Encapsulation. Abstraction is mechanism to show only relevant data to the user. Consider the same mobile example again. Whenever you buy a mobile phone, you see their different types of functionalities as camera, mp3 player, calling function, recording function, multimedia etc. It is abstraction, because you are seeing only relevant information instead of their internal engineering.

We use abstraction in programming languages to make abstract class. Abstract class represents abstract view of methods and properties of class.

Implementation Difference Between Encapsulation and Abstraction

1.  Abstraction is implemented using interface and abstract class while Encapsulation is implemented using private and protected access modifier.

2. OOPS makes use of encapsulation to enforce the integrity of a type (i.e. to make sure data is used in an appropriate manner) by preventing programmers from accessing data in a non-intended manner. Through encapsulation, only a predetermined group of functions can access the data. The collective term for datatypes and operations (methods) bundled together with access restrictions (public/private, etc.) is a class.

3. Example of Encapsulation

Class Encapsulation
{
    private int marks;

    public int Marks 
   {
      get { return marks; }
      set { marks = value;}
    }
}

4. Example of Abstraction

abstract class Abstraction
{
    public abstract void doAbstraction();
}

public class AbstractionImpl: Abstraction
{
    public void doAbstraction()
   {
       //Implement it
   }
}
 

Thursday, 2 May 2013

Difference Between Store Procedure and UDF

Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called. But Function is compiled and executed every time when it is called. 

Basic Difference

  1. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  2. Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  3. Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters..
  4. Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference

  1. Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
  2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
  3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
  4. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  5. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
  6. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
  7. We can go for Transaction Management in Procedure whereas we can't go in Function.

Saturday, 23 March 2013

What is Design Patterns

What are the Design Patterns

Design Patterns are the ways to solve the problems which we getting daily while doing our task.

Design Patterns are the definite solutions for fixed problems

Design Patterns provide the ways how to solves the problems, how to handle this problem.

Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.

Patterns that imply object-orientation or more generally mutable state, are not as applicable in functional programming languages.

Benefits of Design Patterns

1- Speed Up Development Work- Design patterns can speed up the development process by providing tested, proven development paradigms

2- Handle Major Problems - Reusing design patterns helps to prevent subtle issues that can cause major problems, and it also improves code readability for coders and architects who are familiar with the patterns.

Design Pattern Types
Creational
Structural
Behaviour

[Type - Creational]
Singleton Design Pattern















Thursday, 28 February 2013

Child Action in MVC

Child actions are action methods invoked from within a view. This lets you avoid repeating controller
logic that you want to use in several places in the application. Child actions are to actions as partial
views are to views.

Wednesday, 27 February 2013

Asp.net MVC ActionFilter

Action Filters for performing logic either before an action method is called or after its run.

Action Filters are custom attributes that provide a declarative means to add pre-action and post-action behavior to controller action methods.

ActionFilterAttribute is the base class for all the attribute filters. It provides the following methods to execute a specific logic after and before controller action’s execution:- OnActionExecuting(ActionExecutedContext filterContext)
Just before the action method is called
- OnActionExecuted(ActionExecutingContext filterContext):
After the action method is called and before the result is executed (before view render).
- OnResultExecuting(ResultExecutingContext filterContext):
Just before the result is executed (before view render).
- OnResultExecuted(ResultExecutedContext filterContext):
After the result is executed (after the view is rendered).
By overriding any of these methods into a derived class, you can execute your own filtering code.

Wednesday, 20 February 2013

Differnece Between NULL and empty in SQL

Differnece Between NULL and empty in SQL


To indicate that a value has deliberately not been specified, use the NULL keyword. NULL is the preferred way in SQL to indicate that a data value is nonexistent.
The empty string ('') is not the same thing as NULL. An empty string is a specified string. It is the shortest possible string, one that contains no characters. An empty string is represented internally by the non-display character $CHAR(0). Thus NULL and the empty string are different in nature, though in many instances the results of their use are identical. The empty string should be avoided in SQL coding. However, because many SQL operations delete trailing blank spaces, a data value that contains only whitespace characters (spaces and tabs) may be handled as an empty string. If an empty string is explicitly specified as a column default value, this value is represented by the non-display character $CHAR(0).
The SQL empty string, like all SQL strings, can also be represented with double quote characters (""), but this usage should be avoided because of potential conflict with SQL delimited identifiers.
You can convert an empty string to a NULL by using the ASCII function, as shown in the following example:
SELECT DISTINCT NULL AS NullVal,
{fn ASCII('')} AS EmpStrVal
FROM Sample.Person
 
NULL Processing
The NOT NULL data constraint requires that a field must receive a data value; specifying NULL rather than a value is not permitted. This constraint does not prevent the use of an empty string value. For further details, refer to the CREATE TABLE command.
The NULL predicate in the WHERE or HAVING clause of a SELECT statement selects NULL values; it does not select empty string values.
The IFNULL function selects NULL values, it does not select empty string values.
The COALESCE function selects the first non-NULL value from supplied data. It treats empty string values as non-NULL.
When the CONCAT function or the concatenate operator (||) concatenate a string and a NULL, the result is NULL. This is shown in the following example:
SELECT DISTINCT {fn CONCAT('fred',NULL)} AS FuncCat,
'fred'||NULL AS OpCat
FROM Sample.Person
 
The AVG, COUNT, MAX, MIN, and SUM aggregate functions ignore NULL values when performing their operations. (COUNT * counts all rows, because there cannot be a record with NULL values for all fields.) The DISTINCT keyword of the SELECT statement includes NULL in its operation; if there are NULL values for the specified field, DISTINCT returns one NULL row.
The AVG, COUNT, and MIN, aggregate functions are affected by empty string values. The MIN function considers an empty string to be the minimum value, even when there are rows that have a value of zero. The MAX and SUM aggregate functions are not affected by empty string values.
NULL Arithmetic
Any SQL arithmetic operation that has NULL as an operand returns a value of NULL. Thus, 7+NULL=NULL. This includes the binary operations addition (+), subtraction (-), multiplication (*), division (/), integer division (\), and modulo (#), and the unary sign operators plus (+) and minus (-).
An empty string specified in an arithmetic operation is treated as a value of 0 (zero).
The Length of NULL
Within SQL, the length of a NULL is undefined (it returns <null>); the length of an empty string, however, is defined as length zero, as shown in the following example:
SELECT DISTINCT CHAR_LENGTH(NULL) AS NullLen,
CHAR_LENGTH('') AS EmpStrLen
FROM Sample.Person
 
However, certain Caché extensions to standard SQL treat the length of NULL and the empty string differently. The $LENGTH function returns a length of 0 for a NULL, and a length of 1 for an empty string value. This functionality is compatible with Caché ObjectScript:
SELECT DISTINCT $LENGTH(NULL) AS NullLen,
$LENGTH('') AS EmpStrLen
FROM Sample.Person
 
Another place where the internal representation of these values is significant is in the %STRING, %SQLSTRING and %SQLUPPER functions, which append a blank space to a value. Since a NULL truly has no value, appending a blank to it creates a string of length 1. But an empty string does have a character value, so appending a blank to it creates a string of length 2. This is shown in the following example:
SELECT DISTINCT CHAR_LENGTH(%STRING(NULL)) AS NullLen,
CHAR_LENGTH(%STRING('')) AS EmpStrLen
FROM Sample.Person
 

Difference Between MVC2 and MVC3 in Asp.net