Friday, June 6, 2008

Lambda Expressions (sample) - The .Net delegate evolution...

For some strange reason many developers afraid from Lambda, I don't know why exactly but I think it is a great new syntax.
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

A litle bit of background:
In .Net 1.1 we had delegates.
In .Net 2.0 we had anonymous delegates
In .Net 3.5 we have lambda!!! (this is one of the best things that happens in .Net 3.5)

small sample:
List list = new List();
int x = 5;
list.Find(NormalDelegate); //Notmal delegate
private bool NormalDelegate(int number)
{
// can't use anything but members and parameters (number)
return number%2 == 0;
}

list.Find(delegate(int num) //anonymous delegate
{
// can use x - or any thing in the block above plus parameters
return num%2 == 0;
});

list.Find(num => num%2 == 0);
// The lambda syntax we don't need the return word

Lambda:
Well lambda is just a shorter why to write
anonymous delegate
The same code above can be write in lambda easly and very shortly
list.Find(n => n % 2 ==9); //Thats it! one short line
if you want to create something longer it will start to look like anonymous delegate
For example
list.Find(n=> {
n = n + x;
return n % 2 == 0;
});
now we need the return "word" (Not like before)

I hope it explain you abit about lambda

You can read more about Lambda Expressions in the msdn

Enjoy (e=> e == Int32.MaxValue); // :)




Saturday, May 10, 2008

Extension Methods C# .NET 3.5

Extension Methods are new at .NET 3.5 It let you add methods to existent class.

Example:

public static class Extensions
{
public static int ToInt32Ext(this string s) // we add the this word
{
return Int32.Parse(s);
}

public static int ToInt32(string s)
{
return Int32.Parse(s);
}

}

void Main()
{
string s = "5";
int x = s.ToInt32Ext(); // using the extension method
Console.WriteLine(x);
x = Extensions.ToInt32(s);
Console.WriteLine(x);
}

Please notice:
  • The this word must be the first argument in the method,in this example we only have one argument but if you have more remember that it must be the first thing.
  • The class must be a static class.
I think it is a nice feature but doesn't really add new power to the language.



Friday, May 9, 2008

Equals and GetHashCode The Right Way!!!!!

Hi
Recently I witness many mistakes when creating new class. many developers override Object.GetHashCode() in a wrong way!!! that can make error that will be very hard to find. Lets start with the basic rules when writing your own GetHashCode:
  • If X.Eqauls(Y) == true then X.GetHashCode() == Y.GetHashCode(). if two objects are equals they must have the same HashCode.
  • If X.GetHashCode() != Y.GetHashCode() then X.Equals(Y) == false. If two objects has defraent hash code they cant be Equal to each other.
  • object GetHashCode() must NOT be changed during it life cycle. Once the object was created it hash code must NOT change!!!
  • If X.Eqauls(Y) == false then X.GetHashCode() Should (NOT A MUST) be defrant from Y.GetHashCode()
If you creates your own object and overrides Equals you will get an Warning:
Here is an example of a wrong way to make HashCode and what will happen:

class
MyWrongObject
    {
private int m_One;
public int One
{
get { return m_One; }
set { m_One = value; }
}
public MyWrongObject() { }
public MyWrongObject(int one)
{
m_One = one;
}

public override bool Equals(object obj)
{
MyWrongObject other = obj as MyWrongObject;
if (other != null)
return (One == other.One);
else
return false;
}

public override string ToString()
{
return String.Format("MyWrongObject[{0}]", One);
}

public override int GetHashCode()
{
return ToString().GetHashCode();
}


public static void Main(string[] args)
{
HashSet<MyWrongObject> set1 = new HashSet<MyWrongObject>();
MyWrongObject obj1 = new MyWrongObject(1, 1);
set1.Add(obj1);
if (set1.Contains(obj1))
Console.WriteLine("Found obj1");
obj1.One = 2; // This line changes the GetHashCode() of obj1
if (set1.Contains(obj1))
{
// We wont see this line because Contains looks at the GetHashCode()
then at Equals()

Console.WriteLine("You won't see this line");
}
else
Console.WriteLine("Hmmm.. can't find obj1 but obj1 is here");
foreach (MyWrongObject obj in set1)
{
if (obj1.Equals(obj))
Console.WriteLine("obj:{0} Can't find obj1 but obj1 is here", obj);
}
}
}



Please notice that you can't make a setter to a member that changes the GetHashCode() of the object.
If you do that you should think about throwing an exeption when using GetHashCode()

Enjoy,

Wednesday, April 30, 2008

Visual Studio Add-ons (Add-in)

Hi,
I would like to tell you about few Visual Studio add ons that are a must for any developer.
Let's start with the free ones...
1. Test Driven .NET - Let you run any function with a single click No more Main functions for testing your function code just click and go... You can run test, open reflector with a click this is a free download. Trust me it will make you life very easy http://www.testdriven.net/
2. GhostDoc - GhostDoc is a free add-in for Visual Studio that automatically generates XML
documentation comments for C#. Either by using existing documentation inherited
from base classes or implemented interfaces, or by deducing comments from
name and type of e.g. methods, properties or parameters. http://www.roland-weigelt.de/ghostdoc/
3. Resharper - This is add-in is not free but it will save you so much time and energy that will return it cost in less then a week. Great error finder, code optimizer and much more I can write a lot on it but I think you should read more in the site (30 days Trail is available here)
4. Smart paster - let you paste any thing you want as a comment, string, StringBuilder or Region. very nice and easy to use adds another option at the right click menu (download from here)

Enjoy




Friday, April 25, 2008

At last HashSet in .NET 3.5

Hi
A few days ago I found a new collection HashSet (System.Collections.Generic namespace).
I am personally waited for this since I first saw it in JAVA 1.4.2.
HashSet is a combination betwin a Set and A Dictionary. Each element can be found only once. Add, Remove, Contains In O(1) - expected (if no rehash is required) just like Dictionary.
It has some new cool methods like UnionWith, IntersectWith.
Small (and simple) Exmaple:

HashSet<int> theSet1 = new &nbspHashSet<int>();
theSet1.Add(1);
// Return true
theSet1.Add(2); // Return true
theSet1.Add(2); // Return false
// theSet1 contains 1,2

HashSet<int> theSet2 = new HashSet<int>();
theSet2.Add(1);
// Return true
theSet2.Add(3);
// Return true
theSet2.Add(4);
// Return true
// theSet2 contains 1,3,4

theSet1.UnionWith(theSet2);
// theSet1 contains 1,2,3,4

theSet1.IntersectWith(theSet2);
// theSet1 contains 2

  • Unlike ICollection.Add : void In HashSet.Add : bool
If you are using HashSet default constactur then you will get a defult comperator (just like in the example above). One thing that you might like to do is to create your own comperator for example we cna create a odd even comperator

class OddEvenComparer : IEqualityComparer {
public OddEvenComparer() {}
public bool Equals(int x, int y) {
return (x & 1) == (y & 1);
}

public int GetHashCode(int x) {
return (x & 1);
}
}


// Now we will use the comperator
HashSet<int>
oddEvenSet= new HashSet<int>(new OddEvenComparer());
oddEvenSet.Add(1);
// Return true
oddEvenSet.Add(3);
// Return false (we allready have an odd number)
oddEvenSet.Add(4);
// Return true
// oddEvenSet will now hold 1,4 (3 is equal to 1 accurding to our OddEvenComparer)

For more information about HashSet you can read in the MSDN http://msdn2.microsoft.com/en-us/library/bb359438.aspx
For Set definition from Wikipedia:
http://en.wikipedia.org/wiki/Set

Enjoy