Monday, July 20, 2009

C# 4.0: Dynamic Programming



If C# 3.0 was all about Language Integrated Query (LINQ), then C# 4.0 is all about dynamic programming. What exactly does that mean? It means that C# 4.0 brings some of flexibility and declarative style of programming to C#.

But what does that really mean?
To sum it up in one keyword: dynamic.
C# 4.0 is adding a new dynamic keyword which is used as a data type in much the same way the var keyword is used. Why is this important? The biggest reason is that it allows a C# program to use dynamic dispatch to more naturally create objects coming from a dynamic language.
For example, suppose you have a Calculator object declared in C#, meaning it is statically typed. You interact with your object like this:
Calculator calc = GetCalculator();
int sum = calc.Add(10, 20);
That’s pretty simple and straight forward. Now suppose the Calculator is not a statically typed .NET class (or it is a .NET class but you don’t know the specific type of class), you must do something like this:
object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add",
    BindingFlags.InvokeMethod, null,
    new object[] { 10, 20 });
int sum = Convert.ToInt32(res);
That’s not nearly as simple. In fact, it’s downright ugly. There is a lot of non-type-safe calls and reflection going on here that you really shouldn’t have to see.
To take this a step further, if we knew that Calculator was a JavaScript class, you must use similar (but still significantly different) code:
ScriptObject calc = GetCalculator();
object res = calc.Invoke("Add", 10, 20);
int sum = Convert.ToInt32(res);
The reason for the differences in syntax is that there is no unification between the two APIs.
In C# 4.0, you can now use the following syntax:
dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);
If you look at this syntax and the earlier statically typed call, you should notice that the only difference is that in C# we are declaring the data type to be dynamic.

Does this mean that C# is loosing it's roots as a statically typed language or that we should all start moving towards dynamic languages? Absolutely not. What is means is that it is now easier for you to write C# code that talks to objects (or APIs) written in dynamically typed languages. It also means that there is a unified API to talk to any dynamic language. You no longer need to worry about what language you are interoperating with to determine which C# code you must write.
So how does the dynamic keyword work? As I mentioned, it's a keyword in a similar fashion to var. You declare at compile-time the type to be dynamic, but at run-time you get a strongly typed object.

The dynamic keyword is great for writing C# code that consumes a dynamic object, but what about going the other direction and writing C# code that can be called from a dynamic language? You do this by implementing the IDynamicObject interface (or more simply, inheriting from the abstract DynamicObject class) and providing your own implementation for the member lookup and invocation.
Using the features and capabilities of the new dynamic keyword, the IDynamicObject interface, and the fact that the dynamic dispatch can dispatch to both dynamic and static types, C# effectively gets support for duck-typing.


Tuesday, July 14, 2009

Bind CheckedListBox Directly with Datatable in C#

chkListBuilding.Items.Clear();
DataTable dtBuilding = (new BuildingManager()).SelectBuilding();
((ListBox)chkListBuilding).DataSource = dtBuilding;
((ListBox)chkListBuilding).DisplayMember = "BuildingName";
((ListBox)chkListBuilding).ValueMember = "BuildingID";

Check List Box With LINQ + Get Checked IDs Comma Separated

var v = (from b in chkListBuilding.CheckedItems.Cast<listitem>()
select b.Value.ToString());

string BuildingIDs = v.Aggregate(delegate(string item1, string item2)
{
return string.Format("{0}, {1}", item1, item2);
});

Thursday, July 2, 2009

Diffrence Int32.parse, Convert.ToInt32, Int32.TryParse

-------------------Int32.parse(string)-------------------

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent.
When s is null reference, it will throw ArgumentNullException.
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

*******
Example
*******

string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";

int result;
bool success;

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException


-------------------Convert.ToInt32(string)-------------------

Convert.ToInt32(string s) method converts the specified the string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method.
When s is null reference, it will return 0 rather than throw ArgumentNullException
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException

*******
Example
*******

result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException



-------------------Int32.TryParse(string, out int)------------------

Int32.Parse(string, out int) method converts the specified the string representation of 32-bit signed integer equivalent to out variable, and returns true if it parsed successfully, false otherwise. This method is available in C# 2.0
When s is null reference, it will return 0 rather than throw ArgumentNullException.
If s is other than integer value, the out variable will have 0 rather than FormatException.
When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException.

*******
Example
*******

success = Int32.TryParse(s1, out result);
//-- success => true; result => 1234
success = Int32.TryParse(s2, out result);
//-- success => false; result => 0
success = Int32.TryParse(s3, out result);
//-- success => false; result => 0
success = Int32.TryParse(s4, out result);
//-- success => false; result => 0

Convert.ToInt32 is better than Int32.Parse, since it return 0 rather than exception. But, again according to the requirement this can be used. TryParse will be best since it handles exception itself always.