Sunday, August 1, 2010

Tuple in C# 4.0

What is a Tuple?

In Mathematics, A Tuple is a sequence of finite length. An n-tuple is a tuple with n elements. For example (2, 4, 3, 8) is a 4-tuple.

C# 4.0 introduced new data type Tuple. Tuple is not new in software engineering, but of course it is new in dot net frame work 4.0. A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. There are two ways to instantiate Tuple By calling either the Tuple constructor or the static Tuple.Create() method.

// Instantiate using constructor
Tuple<int, string, int> t1 = new Tuple<int, string, int>(3, "Frank", 9);

// Instantiate using create method
Tuple<int, int, int> t2 = Tuple.Create(3, 5, 9);

Tuple constructor and create() method can contains maximum 8 parameters. You have to take care of the 8th parameter because it replaces another tuple object.

Simple use of Tuple

You can easily return more than one value from Method without using out or ref parameters.

public Tuple<int, int> SplitPoints(string point)
string[] pointList = point.Split(',');

int x = Convert.ToInt32(pointList[0]);
int y = Convert.ToInt32(pointList[1]);
return Tuple.Create<int, int>(x, y);

SplitPoints method split the points and returns x and y points in tuple.

Tuple<int,int> points = SplitPoints("12,14");
string msg = string.Format("X: {0}, Y: {1}", points.Item1, points.Item2);

You can get returned values from exposed properties Item1, Item2 etc by Tuple object. Item properties of Tuple object are readonly. You can not change the value of the property.

Friday, February 5, 2010

Lambda Expression in C# 3.0

Lambda Expression is the one of the best feature of the C# 3.0. Lambda expression is same as anonymous method introduced in C# 2.0. Lambda Expression is a concise syntax to achieve the same goal as anonymous method. Now we can summarize Lambda expression in one line.

“Lambda expression is simply a Method.”

Syntax of Lambda Expression

Input Parameters => Expression/Statement Block;

Left hand side of expression contains the zero or more parameters followed by Lambda operator ‘=>’ which is read as “goes to” and right hand side contains the expression or Statement block.

A simple Lambda expression: x => x * 2

This Lambda expression is read as “x goes to x times 2”. Lambda Operator “=>” has sameprecedence as assignment “=” operator. This simple expression takes one parameter “x” and returns the value “x*2”.

Parameters Type

The parameters of the lambda expression can be explicitly or implicitly typed. For example

(int p) => p * 4; // Explicitly Typed Parameter
q => q * 4; // Implicitly Typed Parameter

Explicit typed parameter is same as parameters of method where you explicitly specified the type of parameter. In an implicit typed parameter, the type of parameter inferred from the context of lambda expression in which it occurs.

Type Inference is a new feature of c# 3.0. I will explain it in some other blog.

Use simple Lambda Expression

Here is simple example of Lambda Expression which returns a list of numbers greater than 8.

int[] numbers = {1,2,3,4,5,6,7,8,9,10 };  
var returnedList = numbers.Where(n => (n > 8));

You can also use anonymous method for returning same list.
int[] numbers = {1,2,3,4,5,6,7,8,9,10 };
var returnedList = numbers.Where(delegate(int i) { return i > 8; });

Use Statement Block in Lambda Expression

Here is simple example to write statement block in the lambda expression. This expression returns list of numbers less than 4 and greater than 8.

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var returnedList = numbers.Where(n =>
if (n < 4)
return true;
else if (n > 8)
return true;

return false;

Use Lambda with More then one Parameter

You can also write lambda which takes more than one parameters. Here is an exampleof lambda which adds two integer numbers.

delegate int AddInteger(int n1, int n2);

AddInteger addInt = (x, y) => x + y;
int result = addInt(10,4); // return 14

Use Lambda with Zero parameter

Here is an example of lambda which take no parameter and returns new Guid.
delegate Guid GetNextGuid();

GetNextGuid getNewGuid = () => (Guid.NewGuid());
Guid newguid = getNewGuid();

Use Lambda that return Nothing

You can also write lambda which returns void. Here is an example that lambda is only showing message and return nothing.

delegate void ShowMessageDelegate();

ShowMessageDelegate msgdelegate = () => MessageBox.Show("It returns nothing.");

Some Build in Delegates

Dot Net Framework 3.0 provides some build in parameterized delegate types that is “Func<t>(...)” and also provides some parameterized delegates that returns void that is “Action<T>(...)”.

Monday, February 1, 2010

Extension Method

Last Few days I was thinking how Microsoft added new method in existing classes of visual studio. I was surprised because I was creating List<> and I was showing me some LINQ methods, but when I commented “Using System.Linq” line, it was showing me default list methods.

But when is removed comments “Using System.Linq”. Now Visual Studio was showing me some Linq methods in the intelligence window.

Then I started searching on the web about it. I found new exciting feature of framework 3.0, which is “Extension Methods”. You can extend existing classes without inheritance using extension methods. There are some which you should keep in mind while writing extension method.
  1. You cannot override existing method by writing extension method.
  2. If extension method has same name as instance method then it will not called, because the priority of instance method is high. At compile time extension method has low priority.
  3. You can write extension for Properties, data Members and events.
It is very simple to write extension method. Create static class and write static extension method in this class. The “this” keyword in the parameters tells the compiler to add the extension method in the type after “this” keyword. In my example “this string” compiler adds extension method to the string class.

namespace ExtensionTest
public static class ExtensionOfString
public static bool IsNumber(this string value)
Regex expression =
new Regex(@"^[0-9]([\.\,][0-9]*)?$");
return expression.IsMatch(value);
Here is an example to use extension method. Include the namespace and call your extension method like the original method of the instance.

 using ExtensionTest;
. . . . .

string number = "4";
bool isNumber = number.IsNumber();

You can see how easy it is to write extension method in Dot net.

Monday, January 4, 2010

Show Image in Combo Box

It is very easy to add images in combo box. Dot net provides an easy way to add image. here is an example code.

public static void BindTaskPriorityCombo(ComboBox priorityCombo, bool addEmpty)
priorityCombo.DrawMode = DrawMode.OwnerDrawVariable;
priorityCombo.DrawItem += new DrawItemEventHandler(priorityCombo_DrawItem);

if (addEmpty)

string[] priorities = {"High", "Medium", "Low"};
foreach (string priority in priorities )

static void priorityCombo_DrawItem(object sender, DrawItemEventArgs e)
if (e.Index >= 0)
ComboBox cmbPriority = sender as ComboBox;
string text = cmbPriority.Items[e.Index].ToString();

if (text.Length > 0)
string priority = text;
Image img = GetTaskPriorityImage(priority);

if (img != null)
e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 15, 15);

e.Graphics.DrawString(text, cmbPriority.Font, System.Drawing.Brushes.Black,
new RectangleF(e.Bounds.X + 15, e.Bounds.Y,
e.Bounds.Width, e.Bounds.Height));


public static Image GetTaskPriorityImage(string priority)
switch (priority)
case "High":
return Properties.Resources.High_Priority;
case "Low":
return Properties.Resources.Low_Priority;
case "Medium":
return Properties.Resources.Medium_Priority;


return null;


Call BindTaskPriorityCombo() method to to bind priority combo box. set priorityCombo.DrawMode = DrawMode.OwnerDrawVariable and register Draw item event of combo box using priorityCombo.DrawItem += new DrawItemEventHandler(priorityCombo_DrawItem) from drawing image in combo box item.

For more read my article: