.Net Development&Automated Testing10 Jun 2011 10:10 pm

I just found this gem in a post on another subject on Krzysztof Koźmic’s blog and thought it merited its own post. Beautifully simply solution for asserting that a class doesn’t hold a reference to an object that it should not.

[Fact]
public void Freezable_should_not_hold_any_reference_to_created_objects()
{
    var pet = Freezable.MakeFreezable<Pet>();
    var petWeakReference = new WeakReference(pet, false);
    pet = null;
    GC.Collect();
    Assert.False(petWeakReference.IsAlive, "Object should have been collected");
}
.Net Development02 Apr 2011 07:26 am

This is just a quick plug for a post on Jim Christopher’s blog, beefycode.com, that explains how to create a Unity Extension to support IoC Chaining in much the same way as Castle Windsor does. I am going to need this someday and don’t want to loose the link. Thanks Jim.

.Net Development24 Mar 2011 05:23 pm

This post grows out of my previous post on creating a C# equivalent to the Visual Basic With statement. I have since come up with a hand full of other lambda-accepting extension methods that do other handy things.

Improving on the With Statement

First off, the original with function can be extended to return values if need be as follows:

public static TReturn With<T,TReturn>(this T obj, Func<T, TReturn> action)
{
    return action(obj);
}

The As Method

The following As methods are very handy when you have a variable that is of one type but you need to perform some actions on it in the context of another type which the it also implements.

public static void As<T>(this object obj, Action<T> action)
{
    action((T) obj);
}
 
public static TReturn As<T,TReturn>(this object obj, Func<T, TReturn> action)
{
    return action((T) obj);
}

IfIs, the Conditional form of As

What if you are not sure if the type you have can be cast to the other type? The following IfIs methods are just like the As method but only execute the code if the cast can be made.

public static void IfIs<T>(this object obj, Action<T> action)
{
    if(obj is T)
        action((T) obj);
}
 
public static TReturn IfIs<T,TReturn>(this object obj, Func<T, TReturn> action)
{
    return obj is T ? action((T)obj) : default(TReturn);
}

Again I can see that this sort of syntactical sugar may drive some people nuts. Others may just not see the need. But for some of us, this sort of thing makes it easier to write expressive code.

« Previous PageNext Page »