Showing posts with label Playing with C#. Show all posts
Showing posts with label Playing with C#. Show all posts

Thursday, September 13, 2012

What’s the difference between ‘Dynamic’, ‘Object’ and reflection?

Many developers think that ‘Dynamic’ objects where introduced to replace to ‘Reflection’ or the ‘Object’ data type. The main goal of ‘Dynamic’ object is to consume objects created in dynamic languages seamlessly in statically typed languages. But due to this feature some of its goals got overlapped with reflection and object data type.
Eventually it will replace reflection and object data types due to simplified code and caching advantages. 

Dynamic object is a small feature provided in the DLR engine by which we can make calls to objects created in dynamic languages. The big picture is the DLR which helps to not only to consume, but also your classes can be exposed to dynamic languages.

Object / Reflection
Reflection and Object type is only meant for referencing types whose functions and methods are not know during runtime. Reflection and object type do not help to expose your classes to other languages. They are purely meant to consume objects whose methods are known until runtime

What is Dynamic Type Or define DLR?


Design Time/Compile Time Object:      In .net  programming we can access all the properties and functions at compile time only as illustrated in below example where we are accessing the method of Calculator class(calc.Add(10,20)).
e.g.
Calculator calc = GetCalculator();
Int sum = calc.Add (10, 20);
Run Time Object /Late Binding: In this Case compiler doesn’t checks for compile time error everything is handled at run time. The most important thing is that we can’t access the properties and methods while writing code.

If you wanted to do the exact same thing as in e.g. (like if it were some other class, maybe old-COM interop, or something where the compiler didn't know a priori that Add() was available, etc) you'd do this:
e.g.
object calc = GetCalculator ();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 });
Int sum = Convert.ToInt32 (res);


Before .net 4.0 we are handling any COM Component (dynamically typed languages) as mentioned in e.g. .



We store the COM objects in object Type or in short with the help of reflection and Object Type we till now manage our code while dealing with dynamically typed languages.


DYNAMIC TYPES OR DLR:
DLR (Dynamic language runtime) is set of services which add dynamic programming capability to CLR. DLR makes dynamic languages like LISP, Javascript, PHP,Ruby to run on .NET framework.
Due to DLR runtime, dynamic languages like ruby, python, JavaScript etc can integrate and run seamlessly with CLR. DLR thus helps to build the best experience for your favorite dynamic language. Your code becomes much cleaner and seamless while integrating with the dynamic languages.
E.g. We can write the same code as mentioned in e.g. as below with dynamic Type.


dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);

Please Note here GetCalculator is a COM component method not of the .Net class.

Please follow below links for detail.
http://www.codeproject.com/Articles/42997/NET-4-0-FAQ-Part-1-The-DLR
http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx

 

Wednesday, September 12, 2012

How can we consume an object from dynamic language and expose a class to dynamic languages?

To consume a class created in DLR supported dynamic languages we can use the ‘Dynamic’ keyword. For exposing our classes to DLR aware languages we can use the ‘Expando’ class.

So when you want to consume a class constructed in Python , Ruby , Javascript , COM languages etc we need to use the dynamic object to reference the object. If you want your classes to be consumed by dynamic languages you need to create your class by inheriting the ‘Expando’ class. These classes can then be consumed by the dynamic languages.

For more details please visit below link;
http://www.codeproject.com/Articles/42997/NET-4-0-FAQ-Part-1-The-DLR

Friday, September 7, 2012

What is Optional and Named parameters in C# 4.0?

Optional Parameters: Function containing default values in its declration which can be called with less number of parameters.
e.g.
public static string CheckTicket( bool _isVIP=false,string name="Unknown")
{
//Body of function..}//Above Function can be called like..
}
1. Program.CheckTicket();
2. Program.CheckTicket(true);
3. Program.CheckTicket(true,"Bimlesh");

Named Parameters:  while calling function this provides an option for passing function parameters with any sequence.

e.g.
public static string CheckTicket( bool _isVIP=false,string name="Unknown")

{//Body of function..
}
//Above Function can be called like..
1. Program.CheckTicket(name: "Bimlesh",_isVIP:true);

2. Program.CheckTicket(name:"Bimlesh");

                                                          Sample Code




Tuesday, August 9, 2011

What is Difference Between Out and Ref keyword in C#?


Out & Ref keywords in C# are used for returning multiple values from a function.


Difference:


Out parameter need to be initialized inside the body of a method but not in the case of ref parameter.


Example of Out Keyword



Example of Ref Keyword


Example of Out & Ref Keyword


Saturday, June 11, 2011

Extention Methods in C#?


Extention Methods are special type of Static methods which can be add to existing types without recompiling or modifing the original type.
Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Syntex:
Declare the class and its method as Static and the first parameter of function is preceeded by this key word.
Page 1.
namespace ExtensionMethods
{
public static class Utility
{
public static void Print(this object o)
{
Console.WriteLine("Called print: {0}", o.ToString());
}
public static int Increment(this int i)
{
return i++;
}
public static int Decrement(this int i)
{
return i--;
}
public static int Double(this int i)
{
return i * 2;
}
public static int Bonus(this int i)
{
return i + 5;
}
}
}
Page 2. Client Code
If we want to call the extention methods in our code than we need to first add the namespace of extention method.

namespace UseExtensionMethods
{
using ExtensionMethods;
static class Program
{
static void Main(string[] args)
{
int anotherNumber = 10;
int i = 7;
//e.g 1. Print(i);
i.Print();
//e.g 2.
//In the below line Increment method is directly called on variable anotherNumber.

anotherNumber.Increment();
//e.g 3.
//IN the below step first Method Increment is called and the method o/p is supplied to bonus method than decrement method is called and o/p is
//given to print method and finally result will be print on the screen.

anotherNumber.Increment().Bonus().Double().Decrement().Print();
Console.ReadLine();
}
}
}

What is Anonymous Type in C#?

O/P

Code description:

var runtimeClass=new {ID=1,Name="Bimlesh"};

In this above line we store the object of class in a variable of type var and create the class with new key word without having a hardcoded class name.

Like any other class we can access the properties of Anonymous class by its object .

runtimeClass.Id=1;

runtimeClass.Name="Bimlesh";

Friday, May 27, 2011

ISNULL() Function in C#




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace NullableDataTypes
{
public class Program
{
//Like DataBase ISNULL() Function the "??" operator works
//e.g. ISNULL(null,1) o/p will be 1
//Similarly val3= val1 ?? val2;
//val3 will be val2 if al1=null
public static Object IsNull( object objReplace, object objSearch)
{
Object _newVal = 0;
if (objSearch is string)
{
string val = objReplace as string;
_newVal = val ?? objSearch as string;
}
else if (objSearch is int)
{
int? val = objReplace as int?;
_newVal = val ?? objSearch as int?;
return _newVal;
}
else if (objSearch is double)
{
double? val = objReplace as double?;
_newVal = val ?? objSearch as double?;
return _newVal;
}
else if (objSearch is float)
{
float? val = objReplace as float?;
_newVal = val ?? objSearch as float?;
return _newVal;
}
else if (objSearch is decimal)
{
decimal? val = objReplace as decimal?;
_newVal = val ?? objSearch as decimal?;
return _newVal;
}
else if (objSearch is long)
{
long? val = objReplace as long?;
_newVal = val ?? objSearch as long?;
return _newVal;
}
else if (objSearch is bool)
{
bool? val = objReplace as bool?;
_newVal = val ?? objSearch as bool?;
return _newVal;
}
else
{
_newVal = -1;
return _newVal;
}
return _newVal;
}
static void Main(string[] args)
{
/**
* We are storing the returned value in Annoynoumus Type variable
*/
var b = IsNull(null, "Bimlesh");
Console.WriteLine("{0}",b);
Console.Read();
}
}
}

Tuesday, May 24, 2011

How to Check Null Values in C#?



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace NullableDataTypes
{
class Program
{
public static bool CheckNull(object obj)
{
bool _isNull = false;
if (obj is string)
{
//Only Checks For String value
}
else
{
int? X = obj as int?;
//OR int? X = (int?)arr[i];
//Note: X.HasValue returns false for reference type and Null values.
if (X.HasValue)
{
_isNull = false ;
}
else { _isNull = true; }
}
return
_isNull;
}
static void Main(string[] args)
{
bool isnull=Program.CheckNull
("");
Console.WriteLine("Is Supplied Value SPACE is null? -{0}", Program.CheckNull(" "));
Console.WriteLine("Is Supplied Value Bimlesh is Null? -{0}", Program.CheckNull("Bims"));
Console.WriteLine("Is Supplied Value NULL is null? -{0}", Program.CheckNull
(null));
Console.WriteLine("Is Supplied Value 1 is null? -{0}", Program.CheckNull
(1));
Console.
Read();
}
}
}

Friday, May 20, 2011

What is Nullable Numeric DataType?

Defination: Nullable DataTypes are the Types Which can hold Null Value e.g Int, Decimal, Float ,long, bool
Why Required?
Many times we are not confirmed that coming values are Null or Proper.
e.g If Table colm is allowed null and its Type is Int in that case assignment of data into int Type will
be fail (int=Null)
Syntex: Type + ? e.g int?,bool?,long? etc
Nullable Numeric DataTypes e.g Float ,Int, long,Decimal
int? _nullableName;
int _name1;
_nullableName = null;
_name1 = (int)_nullableName;
Console.WriteLine(_name1.ToString());
//Note: If Nullable DataType is having Null value and we are assinging it to some Not Nullable type ,it will throw exception
int standardInteger = 123;
int?
nullableInteger;
decimal standardDecimal = 12.34M;
// Implicit conversion from int to int?
nullableInteger =
standardInteger;
// Explicit conversion from int? to int
standardInteger = (int)
nullableInteger;
// Explicit cast from decimal to int?
nullableInteger = (int?)standardDecimal;