views:

118

answers:

1

Gojko Adzic posted today on his blog about Steve Freeman's unit-testing trick, which helped make it crystal clear why the date comparison in the unit test failed. Here is the blog post describing the trick - it is not long.

The key part of the trick is this method (in Java), which overrides ToString() on a particular instance of the Date class.

private Date namedDate(final String name, final Date date) {
    return new Date(date.getTime()){
        @Override
        public String toString() {
            return name;
        }
    };
}

It appears that this method uses a facility of Java language that doesn't have a match in C# (or at least one that I know of). If you could show me how to do the same trick in C#, that would be awesome.

+4  A: 

That is called an anonymous class in Java. It is really just a class implementation with no name, that overrides ToString()

You would be able to the same in C# with a normal, named class - the only problem being, that DateTime is a struct in C#, so you cannot inherit from it.

C# does have anonymous types, but not in the same way as Java. In C# you can have an anonymous type and specify it's properties, but you cannot specify any method implementations. Therefore, anonymous types in C# and Java tends to be used for different things.

Edit

Here is an example on how you would do it in C#, but as stated above, you cannot do it on DateTime (or other structs, or sealed classes) in C#. So for the sake of the example; I am using an imaginary class called Token, that has a single string property "Value":

private Token GetNamedToken(Token t, string name)
{
    return new NamedToken {Value = t.Value, Name = name};
}

private class NamedToken : Token
{
    public string Name { get; set; }
    public override string ToString()
    {
        return Name;
    }
}
driis
Similarly, this trick wouldn't work for any primitive wrapper in Java (Integer, Double, etc) because they are marked final.
Mark Peters
DateTime is not a class, it is a struct (value type).
Steve Ellinger