.comment-link {margin-left:.6em;}

I Hate Linux

Saturday, August 04, 2007

Let down by Extension Methods

Why haven’t been able to follow as many of the new developments in Visual Studio 2008 as I would have liked, one feature that I was pretty thrilled about is extension methods (ScottGu explains them here).

I just had to read a bit of ugly code to compare your IP addresses and see if a given IP address is in a range and because I want to be compatible with IPv6 I can’t just compare the numerical values of the IP addresses some bass could going through abide by byte of each.

Ugly.

When I got all done I wondered if I could use extension methods in C# 3.0 to make this work better so I quickly banged out this class as a quick test: 

public static class IPAddressExtensionMethods
{
public static bool operator ==(this IPAddress ip1, IPAddress ip2)
{
return true;
}

public static bool operator !=(this IPAddress ip1, IPAddress ip2)
{
return true;
}

public static bool operator >(this IPAddress ip1, IPAddress ip2)
{
return true;
}

public static bool operator <(this IPAddress ip1, IPAddress ip2)
{
return true;
}
}

Bad news for me as the code above fails to compile, not because extension methods themselves don't allow operator overloading, but because extension methods must be in a static class and static classes do not allow user-defined operators.


One way around this would be to actually define methods and not operators:


public static class IPAddressExtensionMethods
{
public static bool AreEqual(this IPAddress ip1, IPAddress ip2)
{
return true;
}

public static bool AreNotEqual(this IPAddress ip1, IPAddress ip2)
{
return true;
}

public static bool GreaterThan(this IPAddress ip1, IPAddress ip2)
{
return true;
}

public static bool LessThan(this IPAddress ip1, IPAddress ip2)
{
return true;
}
}

Unfortunately while this example works, it's rather inelegant...  But still far more elegant than how my C# 2.0 code looks.


I suppose this leaves the question, should you be able to define/overload an operator in an extension method?


Personally I think us is doing so is a logical extension of what extension methods do in the first place... But then that's only my opinion and thankfully though I'm not alone as from the looks of it this issue has already been submitted over on Connect and is something they may come back looking at again to after Visual Studio 2008 ships.

0 Comments:

Post a Comment

<< Home