Category: code snippets

Implicit casting of generic classes

Can anyone tell me what am I missing here? Here’s a simple class

public class Mock<TType>

{

    private readonly TType _actual;

 

    public Mock(TType actual)

    {

        _actual = actual;

    }

    public TType Actual

    {

        get { return _actual; }

    }

    public static implicit operator TType(Mock<TType> item)

    {

        return item.Actual;

    }

}

That’s a generic class that defines implicit casting operator to it’s generic parameter, no magic here. The code compiles without warning. Methods like this one:

 

public TType ThisWorks<TType>()

{

    return new Mock<TType>(default(TType));

}

work as well.

What’s even more stunning, whereas this works:

Mock<string> mock1 = _mocks.Mock<string>();

string actual1 = mock1;

This doesn’t:

Mock<ISomethingUseful> mock2 = _mocks.Mock<ISomethingUseful>();

ISomethingUseful actual2 = mock2;

producing error message:

Error    1    Cannot implicitly convert type ‘Mocks.Mock<Mocks.ISomethingUseful>’ to ‘Mocks.ISomethingUseful’. An explicit conversion exists (are you missing a cast?)

Am I missing something here? Why does it say ‘explicit conversion exists’ when I created implicit conversion? Why it doesn’t work for the interface when it works for string?

[UPDATE:]

According to chapter 6.4.4 of C# 3.0 Language specification you just can’t have implicit conversion to an interface. This in yet another time when I hit an invisible wall trying to do something with generics…

And if you thought that

public class MyClass<TType>:TType

{

}

could be a solution: it isn’t – this won’t compile as well.

Technorati Tags: ,

Strongly Typed EventRaiser with Rhino.Mocks

I’ve been playing in my limited spare time with Rhino.Mocks, trying to come up with a way to simplify interactions with events, and creating strongly typed IEventRaiser (or something similar). Here’s what I’ve come up with so far:

Strongly typed Rhino.Mocks Event invocation 

It’s not an easy task, but I have few ideas. If you have any ideas or suggestions post them in the comments. I’ll submit it to Ayende, so if he likes it you may actually see this stuff in some future version of Rhino.Mocks.

Technorati Tags:

More on inline initialization

Let’s play. What will this program output to the console:

namespace Test

{

    public class Program

    {

        private static void Main()

        {

            System.Console.WriteLine(MyClass.Field);

        }

    }

 

    public class MyClass

    {

        private static readonly int _height = 3;

        private static readonly int _width = 2;

        public static readonly int Field = _width*_height;

    }

}

Do I hear ‘6’? Ok, this was easy. And how about this one?

namespace Test

{

    public class Program

    {

        private static void Main()

        {

            System.Console.WriteLine(MyClass.Field);

        }

    }

 

    public class MyClass

    {

        private static readonly int _height = 3;

        public static readonly int Field = _width * _height;

        private static readonly int _width = 2;

    }

}

Any guess (without actually running the code)?
Technorati Tags:

Framework Tips VIII: Initializing Dictionaries and Collections

In .NET < 3.5 the only collections you could initialize inline were arrays. So this was legal:

public class CollectionTest

{

    public static readonly ICollection<string> _list = 

        new string[]{"one","two","three"};

}

However if you wanted to have List instead of array, you had to use a trick and pass array as constructor parameter:

public static readonly ICollection<string> _list = 

    new List<string>(new string[]{"one","two","three"});

Not the most elegant piece of code, but at least it works. So far so good. What if you wanted to have a IDictionary instead of ICollection? Well… in this case you’re out of luck, at least partially. To have a dictionary initialized, you’d have to use explicit static constructor, and it means – performance hit. Still, it’s better than nothing.

public class CollectionTest

{

    public static readonly IDictionary<string,int> _dictionary = 

        new Dictionary<string,int>();

    static CollectionTest()

    {

        _dictionary.Add("one",1);

        _dictionary.Add("two",2);

        _dictionary.Add("three",3);

    }

}

But this all was in medieval timessmile_wink. Now, with object and collection initializers you can initialize any ICollection, the way you could with Arrays.

private static readonly ICollection<string> _list = 

    new List<string> {"one", "two", "three"};

This is neat, but even better stuff, is that you can do similar thing with Dictionaries, which means, no explicit static constructor required anymore.

private static readonly IDictionary<string, int>

    _data = new Dictionary<string, int>

            {

                {"one", 1},

                {"two", 2},

                {"three", 3}

            }:

Technorati Tags:

C# tricks: Array initialization in C# 3.0

I found pretty slick new feature in C# 3.0 that I haven’t seen anyone mentioning before.

In C# 2.0 to initialize List<T> inline you had to use arrays, like

List<string> keys = new List<string>(new string[]{"key1"});

As you probably already know, in C# 3.0 you can initialize collections in in similar way like you did with arrays in C# 2.0:

List<string> keys = new List<string>(){"key1"};

This has been said many times in many places. What I missed however, was that syntax for initializing arrays changed as well. Now you can simply write:

string[] keys = new[]{"key1"};

Did you know that?

Technorati Tags: ,

C# tricks: set and return in one line

I found nice trick. Instead of writing:

private string SetNewName()

{

    string newName = GetName();

    _name = newName;

    return newName;

}

you can write

private string SetNewName()

{

    return _name = GetName();

}

And it works exactly the same. Slick.

Technorati Tags:

Testing callbacks with Rhino.Mocks

I’m currently writing tests for a piece of code that has lot of events flying here and back. Something like:

public class Caller

{

    public event EventHandler<CancelEventArgs> MyEvent;

 

    public void Call()

    {

        if (MyEvent != null)

            MyEvent(null, new CancelEventArgs(false));

    }

}

If I not only want to test if the event was fired but also examine it’s arguments I end up writing quite a lot of code to do simple thing.

First I have to define IEventSubscriber interface (contrary to IEventRaiser).

public interface IEventSubscriber<TEventArgs> where TEventArgs : EventArgs

{

    void Method(object sender, TEventArgs e);

}

Next I have to initialize it in my SetUp method

 

[SetUp]

public void SetUpTests()

{

    _mocks = new MockRepository();

    _subscriber = _mocks.CreateMock<IEventSubscriber<CancelEventArgs>>();

}

This is however quite dumb plumbing code, and I have to write it once (or once per TestFixture, in case of initialization). The worst part are the tests alone:

[Test]

public void When_Call_called_Caller_should_raise_MyEvent_with_cancel_set_to_false()

{

    using (_mocks.Record())

    {

        Expect.Call(delegate { _subscriber.Method(null, null); }).IgnoreArguments().Do(

            new EventHandler<CancelEventArgs>(

                delegate(object o, CancelEventArgs e) { Assert.IsFalse(e.Cancel); }));

    }

   using (_mocks.Playback())

   {

       Caller caller = new Caller();

       caller.MyEvent += _subscriber.Method;

       caller.Call();

   }

}

My concern is that lines 6-8 are just one big blob of code, and you have to read it carefully, to find out what it actually does. Another thing is inability to use anonymous delegates where type Delegate is expected, which results in more verbose, less readable code.

After writing few tests like this I decided to do something with this ugly piece of code, and thanks to the magic of generics I came up with a helper method:

private void ExpectCallback<TEventArgs>(IEventSubscriber<TEventArgs> subscriber, EventHandler<TEventArgs> handler)

    where TEventArgs : EventArgs

{

    Expect.Call(delegate { subscriber.Method(null, null); }).IgnoreArguments().Do(handler);

}

With it I can shorten my tests to look much nicer:

[Test]

public void Test_Callback_in_C_Sharp_20()

{

    using(_mocks.Record())

    {

        ExpectCallback(_subscriber,

                       delegate(object o, CancelEventArgs e) { Assert.IsFalse(e.Cancel); });

    }

    using(_mocks.Playback())

   {

       Caller caller = new Caller();

       caller.MyEvent += _subscriber.Method;

       caller.Call();

   }

}

and with lambdas, even to:

[Test]

public void Test_Callback_in_C_Sharp_30()

{

    using (_mocks.Record())

    {

        ExpectCallback(_subscriber, (o, e) => Assert.IsFalse(e.Cancel));

    }

    using (_mocks.Playback())

    {

       Caller caller = new Caller();

       caller.MyEvent += _subscriber.Method;

       caller.Call();

   }

}

It not only improves readability of my code, but thanks to generic constraints I get more compile-time type checking. Now I can get back to testing:)

Technorati Tags: , ,

Framework Tips VII: Splitting strings

Joe Developer once had to read options from configuration file, where each line looked basically like this:

option:   first;second;third;;fifth;

Each line consisted of option name, followed by few spaces, and its parameters delimited by semicolons. Now the question is: how would Joe get to those parameters? The most elegant way would be using Regular Expressions, but Joe has strong allergy to them. For this simple example String.Split method will do.

Joe rolled up his sleeves and crafted that beautiful masterpiece of code:

string options = @"option:   first;second;third;;fifth;";

string[] strings = options.Split(';');

foreach (string s in strings)

    Console.WriteLine(s);

    

Console.WriteLine("That's all. Press any key to exit.");

Console.ReadKey(false);

However, that didn’t work quite as well as expected:

string.split.ss0

Joe successfully split each option to different line, but he had also some empty lines, as well as additional stuff along with first option. Fortunately Joe noticed that thanks to params keyword, he can pass more parameters to Split method. He quickly altered his code, by adding two more split characters, and changing foreach loop to for, to leave option element out.

string options = @"option:   first;second;third;;fifth;";

string[] strings = options.Split(';', ':', ' ');

for (int i = 1; i < strings.Length; i++)

    Console.WriteLine(strings[i]);

 

Console.WriteLine("That's all. Press any key to exit.");

Console.ReadKey(false);

string.split.ss1 Proud of himself Joe ran his program to notice, that the output, while better, still didn’t look as he needed. While he managed to get each parameter into its own line, he still got those annoying empty lines.

His immediate idea was to add a condition, to check wether given string is empty before writing it out, but then he remembered the quote:

When debugging, novices insert corrective code; experts remove defective code.  ~Richard Pattis

And since Joe was a true expert, he decided to remove the defect. He looked here and there, and discovered, that StringSplitOptions enum, was exactly what he needed. Fortunately, there was even an overload of Split method that accepted StringSplitOptions as one of its arguments. Joe quickly altered 2nd line of  his code to:

string[] strings = options.Split(new char[] {';', ':', ' '}, StringSplitOptions.RemoveEmptyEntries);

string.split.ss2 And he finally was happy with what he saw when he ran the program. His happiness didn’t last quite long, however. Only ’till he met his boss, to be exact, who told him, that only first two parameters are important, and all remaining should be left out.

I can do it! – Joe thought. – All I need to do is to limit the for loop to stop after two first elements. Then he thought – Why waste resources and time to split further, when all I need are just two first parameters. – He recalled the quote once again, and decided, that as true expert he would find another solution.

Then he found yet another overload, of Split method, that accepted additional parameter: integer, specifying maximum number of substrings to be produced. Joe quickly adjusted his code to the new requirements:

string options = @"option:   first;second;third;;fifth;";

string[] strings = options.Split(new char[] {';', ':', ' '}, 4, StringSplitOptions.RemoveEmptyEntries);

for (int i = 1; i < strings.Length && i < 3; i++)

    Console.WriteLine(strings[i]);

 

Console.WriteLine("That's all. Press any key to exit.");

Console.ReadKey(false);

Now he was really proud of himself – with one simple method, he was able to accomplish the task.

Technorati Tags: ,

Hello World: the ‘new’ keyword

Everyone knows what the new keyword is for in C# – you use it to call constructor of an object, right? What can be simpler? Actually, that’s true, but not the whole truth. That’s the most common way to use it. However, new is one of contextual keywords, which means, it can have different meaning, depending on the context where it’s being used.

The new keyword can be used in three scenarios:

  • the one presented above, everyone immediately thinks of – creating objects.
  • as modifier, to hide members of a base class.
  • as generic constraint.

Creating objects is pretty straightforward, and there’s no magic there:

string[] stringArray = new string[] { "kot", "knur", "pies" };  //creating array

List<string> stringList = new List<string>(stringArray);        //creating class

DateTime dateTime = new DateTime(2000, 1, 1);                   //creating struct

Action myDelegate = new Action(delegate { });                   //creating delegate

var myAnonymousType = new { A = 1, Name = "My name" };          //creating anonymous type

The only thing that may look unfamiliar, is new C# 3.0 anonymous types initializing. It works in similar way to anonymous delegates. Here I created a nameless class, that two fields: A (of type int) and Name (of type string). This is the most basic stuff.

Not everyone however, knows about two other usages of that keyword. Let’s consider very simple example:

class Program

{

    static void Main(string[] args)

    {

        InheritedClass inherited = new InheritedClass();

        inherited.Write();

        UseBaseWrite(inherited);

    }

 

    public static void UseBaseWrite(BaseClass item)

    { item.Write(); }

}

 

public class BaseClass

{

    public void Write()

    { Console.WriteLine("Hello. I'm a BaseClass' Write!"); }

}

 

public class InheritedClass : BaseClass

{

    public new void Write()

    { Console.WriteLine("Hello. I'm a InheritedClass' Write!"); }

}

We have two classes, BaseClass, and InheritedClass that inherits from BaseClass. They both have non-virtual method Write, that writes a string to the console, and inherited class has a new keywords as its modifier (the code would actually work the same without that keyword, we would however receive compile time warning). We then create InheritedClass’ instance, and pass it to UseBaseWrite, method, that calls its Write method.

So what would be the outcome of that program?

Hello. I’m a InheritedClass’ Write!

Hello. I’m a BaseClass’ Write!

 

If you bet on that answer you can give yourself a reward. Now the question for those of you who guessed differently is – why? Notice that Write in BaseClass is not virtual, and as such we’re not overriding it in InheritedClass. We just create brand new method, that has no connection whatsoever to BaseClass’ Write, except the fact that it has the same name. This way,(as InheritedClass inherits from BaseClass) we have in it two unrelated methods with the same name. And here comes the tricky part: Which one of those two methods will be called, depends on the type of reference you’re holding to your object. If you reference it as InheritedClass (as we did in 6th line), we call Write implemented in InheritedClass. When we however reference the same object as BaseClass (as we did in 10th line) BaseClass’s implementation gets called. That’s why new is not inheritance modifier, but it let’s you have method in inherited class with the same name as base class, you don’t get however polymorphic  behavior. In this context it’s usability is really limited.

More interesting usage is new as generic constraint:

static void Main(string[] args)

{

    GenericClass<DateTime> d = new GenericClass<DateTime>();//ok

    DateTime dateTime = d.GetNewItem();

    GenericClass<string> s = new GenericClass<string>();//compile error

}

 

public class GenericClass<T> where T : new()

{

    public T GetNewItem()

    {

        return new T();

    }

}

When you specify new() on constraints list for your generic type, you demand, that generic type T has to have public parameterles constructor.

In the example above, it’s ok to pass DateTime as generic parameter, as it meets the constraint. String however does not have default constructor, that’s why this code would fail to compile.

It let’s you then call new T() anywhere in your code. It can be very useful sometimes. One more thing to keep in mind, is that when you specify more than one generic constraint, new() must be the last one of them.

//compilation error

public class GenericClass<T> where T :  new(), IEnumerable

{ public T GetNewItem() { return new T(); } }

 

//now ok

public class GenericClass<T> where T : IEnumerable, new()

{ public T GetNewItem() { return new T(); } }

And that’s basically all. I hope it was informative and I didn’t miss anything. Happy coding.

Technorati Tags: , , ,

Framework Tips V: Extension Methods and nulls

You can call extension methods on null elements. It’s obvious when you think about it: its a normal static method where you specify its first parameter with this.

using System;

 

namespace ExtensionMethods2

{

    class Program

    {

        static void Main(string[] args)

        {

            string isNull = null;

            Console.WriteLine(isNull.IsNullOrEmpty());

            string isNotNull = "string";

            Console.WriteLine(isNotNull.IsNullOrEmpty());

        }

    }

 

    public static class StringExtensions

    {

        public static bool IsNullOrEmpty(this string s)

        {

            return s == null || s == "";

        }

    }

}

Notice that if it was normal instance method (i.e. defined in the System.String class) I would have to check if my string instance is not null, before calling it, or I would receive runtime NullReferenceException. Now I can move that check to the method, where it belongs, and make my code cleaner. Pretty slick 😉