Thursday 29 October 2009

Cool Generic Delegates in C#

Here are some cool generic delegates (.NET 3.5) I find useful in my day to day coding.

  • Action Delegate
    • Action
    • Action(T)
    • Action(T1, T2)
    • Action(T1, T2, T3)
    • Action(T1, T2, T3, T4)
  • Predicate Delegate
    • Predicate<T>(T obj)
  • Func Delegate
    • Func<T, TResult>
    • Func<T1, T2, T3, T4, TResult>
    • Func<T1, T2, T3, TResult>
    • Func<T1, T2, TResult>
    • Func<TResult>

ACTION DELEGATE

The Action delegate encapsulates a method that has no return value and accepts up to four parameters. Action alone represents no parameter, Action(T), Action(T1, T2) etc… represents the number of parameters.

Simple example: using Action to replace Console.WriteLine, because Console.WriteLine accepts a single string parameter, we can simply assign it to the Action<string> and call action(“ABC”) which is equivalent to the Console.WriteLine(“ABC”)

static void Main(string[] args)

{

Action<string> action = Console.WriteLine;

action("ABC");

Console.ReadLine();

}

Or you can pass the action as a parameter and use it as such, using lambda, which will print “stringA1” to the console:

static void Main(string[] args)

{

DoSomething((s, n) =>

{

Console.WriteLine(s + n);

});

Console.ReadLine();

}

private static void DoSomething(Action<string, int> action)

{

string rawString = "stringA";

int rawNumber = 1;

action(rawString, rawNumber);

}

PREDICATE DELEGATE

The Predicate(T) delegate encapsulates a method that returns a Boolean value and accepts a single parameter.

A simple example:

static void Main(string[] args)

{

Predicate<byte> predicate = bit =>

{

return bit == 1 ? true : false;

};

// This will return true

Console.WriteLine(predicate(1));

// This will return false

Console.WriteLine(predicate(0));

Console.ReadLine();

}

In fact, most LINQ Queries uses this predicate delegate, one simple example is the .Find method:

static void Main(string[] args)

{

var list = new List<string>()

{

"a",

"b"

};

string a = list.Find(i => i == "a");

Console.WriteLine(a);

Console.ReadLine();

}

Another useful usage is in LINQ statements like so:

var list = new List<int>()

{

1,

2

};

Predicate<int> p = val => val == 1;

var i = from item in list

where p(item)

select item;

FUNC DELEGATE

The Func delegate is the most powerful of the lot. A Func can return any type (TResult) and accepts zero or up to four input parameters.

var list = new List<string>

{

"one",

"two",

"three"

};

// This indicates a return type of boolean, and accepts

// two input parameters of IEnumerable<string> and string

// respectively.

Func<IEnumerable<string>, string, bool>

funcPredicate = (collection, item) =>

{

if (collection != null && collection.Count() > 6)

{

return collection.Contains("one");

}

return false;

};

var i = from item in list

where funcPredicate (list, item)

select item;

There you have it, the useful delegates you will definitely find handy!

Other delegates I will cover in a later post will include Expression<T>, EventHandler<TEventArgs>, Converter<TInput, TOutput> and Comparison<T>.

Have fun coding!

Tuesday 20 October 2009

Customised Search Results in Visual Studio

Are you constantly annoyed by the very long File path in the Find Results Window when searching through the File/Project/Solution in Visual Studio?

I found a registry hack to shorten the display path:

1) Type Regedit in "Run"
2) Navigate to HKCU\Software\Microsoft\VisualStudio\9.0\Find
3) Add a new string item called Find result format with a value of $f$e($l,$c):$t\r\n

And here’s the full list of items you can specify in the registry

Files
$p path
$f filename
$v drive/unc share
$d dir
$n name
$e .ext

Location
$l line
$c col
$x end col if on first line, else end of first line
$L span end line
$C span end col

Text
$0 matched text
$t text of first line
$s summary of hit
$T text of spanned lines

Char
\n newline
\s space
\t tab
\\ slash
\$ $

Modify at your own risk! Please back up your registry before making any changes.

How to create a throwaway project in Visual Studio

If you need to create a temp project to try things out in Visual Studio without auto saving it into the Projects directory, go to
1) Tools
2) Options
3) Projects and Solutions
4) General
5) Uncheck (Save new project when created)

Thats it!

Visual Studio 2010 & .Net 4 Beta 2 is Out

Visual Studio 2010 is out and will be made available for download starting Wednesday, and immediately for MSDN Subscriber.

As per Scott Gu's blog, here is an overview of the product lineup specifications:

VS 2010 Product Line SKU Simplifications

With VS 2010 we are simplifying the product lineup and pricing options of Visual Studio, as well as adding new benefits for MSDN subscribers. With VS 2010 we will now ship a simpler set of SKU options:

  • Visual Studio Express: Free Express SKUs for Web, VB, C#, and C++
  • Visual Studio 2010 Professional with MSDN: Professional development tools as you are used to today with the addition of source control integration, bug tracking, build automation, and more. It also includes 50 hours/month of Azure cloud computing.
  • Visual Studio 2010 Premium with MSDN: Premium has everything in Professional plus advanced development tools (including richer profiling and debugging, code coverage, code analysis and testing prioritization), advanced database support, UI testing, and more. Rather than buying multiple “Team” SKUs like you would with VS 2008, you can now get this combination of features in one box with VS 2010. It also includes 100 hours/month of Azure cloud computing.
  • Visual Studio 2010 Ultimate with MSDN: Ultimate has everything in Premium plus additional advanced features for developers, testers, and architects including features like Intellitrace (formerly Historical Debugging), the new architecture tools (UML, discovery), test lab management, etc. It also includes 250 hours/month of Azure cloud computing.
Additionally, Silverlight Toolkit October 2009 has be released with main changes for better Visual Studio 2010 integration. Click here to get it http://silverlight.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30514#ReleaseFiles

Monday 19 October 2009

How to implement a merge sort on a Doubly Linked List using C#

I have been working on a custom linked list recently and required a sorting algorithm to sort the doubly linked list.

Mergesort works better on linked lists than it does on arrays. It avoids the need for the auxiliary space, and becomes a simple, reliably O(N log N) sorting algorithm. And as an added bonus, it's stable too.

Here is a quick merge sort algorithm in C#.Net 3.5 (Note - T is my custom node interface) :

private T Merge_Sort(T first)

{

if (first == null || first.Next == null)

return first;


T second = Split(first);

first = Merge_Sort(first);

second = Merge_Sort(second);

return Merge(first, second);

}

private T Split(T item)

{

if (item == null || item.Next == null)

return null;

T second = item.Next;

item.Next = second.Next;


second.Next = Split(second.Next);

return second;

}

private T Merge(T first,

T second)

{

if (first == null)

return second;


if (second == null)

return first;

// If both are not null, we will run the comparer

// If first is less than second

if (first.CompareTo(second) < 0)

{

first.Next = Merge(first.Next, second);

first.Next.Previous = first;

first.Previous = default(T);


return first;

}

else

{

second.Next = Merge(first, second.Next);

second.Next.Previous = second;

second.Previous = default(T);

return second;

}

}

For the full implementation of the Custom Doubly Linked List, look at this post.