Category Archives: C#

Enhanced enums in C#

This will be an evolving post, hopefully. (If no-one comments on it, it probably
won’t change unless I come up with better ideas myself.) Since working on a Java
project last year, I’ve been increasingly fed up with C#’s enums. They’re really
not very object oriented: they’re not type-safe (you can cast from one enum to
another via a cast to their common underlying type), they don’t allow any
behaviour to be specified, etc. They’re just named constant integral values.
Until I played with Java
1.5’s enum support
, that wouldn’t have struck me as being
a problem, but (at least in some cases) enums can give you so much more. This post
is a feature proposal for C# 4.0. (I suspect the lid for this kind of thing is closed
on 3.0.)

What’s the basic idea?

Instead of being a fixed set of integral values, imagine if enums were a fixed set of
objects. They could have behaviour (and state of sorts), just like other objects – the
only difference would be that there’d only ever be one instance for each value. When
I say they could have “state of sorts” I mean that two values of an enum could differ
in just what they represented. For instance, imagine an enumeration of coins – I’ll use
US coins for convenience for most readers. Each value in the enum would have a name
(Cent, Nickel, Dime, Quarter, Dollar) and a monetary value in cents (1, 5, 10, 25, 100
respectively). Each might have a colour property too, or the metal they’re made of. That’s
the kind of state I mean. In fact, there’s nothing in the proposal below to say that the
state within an enum has to stay the same. I’d recommend that it did stay the same,
but maybe someone’s got an interesting use case where mutable enums would be useful.
(Actually, it’s not terribly hard to think of an example where the underlying state mutates
even if it doesn’t appear to from a public property point of view – some properties could
be lazily initialised if they might take time to compute.)

As well as properties, the enum type could have methods, just as other types do. For instance,
an enumeration of available encryption types may have methods to encrypt data. (I’m giving
fairly general examples here – in my experience, the actual enums you might use tend to be
very domain-specific, and as such don’t make good examples. I’m also trying to steer well
clear of risking giving away any intellectual property owned by my employer.)

Now, consider the possibilities available when you bring polymorphism into the picture. Not
every implementation of a method has to be the same. Some enum values may be instances of
a type derived from the top-most one. This would be limited at compile-time to make enums
fixed – you couldn’t derive from an enum type in the normal way, so you’d
always know that if you had a reference to an instance of the enum type, you’d got one of
the values specified by the enum.

What’s the syntax?

I propose a syntax which for the simplest of cases looks very much like normal enumerations,
just with class enum instead of enum:

public class enum Example
{
    FirstValue,
    SecondValue;
}

Note the semi-colon at the end of the list of values. This could perhaps be optional,
but when using the power of “class enums” (as I’ll call them for now) in a non-trivial way,
you’d need them anyway to tell the compiler you’d reached the end of the list of values,
and other type members were on the way. The next step is to introduce a constructor and
a property:

public class enum Coins
{
    Cent(1),
    Nickel(5),
    Dime(10),
    Quarter(25),
    Dollar(100);
    
    // Instance variable representing the monetary value
    readonly int valueInCents;
    
    // Constructor - all enum constructors are private
    // or protected
    Coins(int valueInCents)
    {
        this.valueInCents = valueInCents;
    }
    
    public int ValueInCents
    {
        get { return valueInCents; }
    }
}

Now, there would actually be some significant compiler magic going on at this point. Each of
the generated constructor calls would actually have an extra parameter – the name of the value. That
parameter would be present in every generated constructor, and if no constructors were declared, a protected
constructor would be generated which took just that parameter. Each constructor would implicitly
call the base constructor which would stash the name away and make it available through a Name
property (and no doubt through calls to ToString() too). What’s the base class in this case?
System.ClassEnum or some such. This could be an ordinary type as far as the CLR is concerned,
although language compilers would be as well to prevent direct derivation from it. This leaves room for
some compilers to allow types which aren’t really enums to derive from it, but does have the advantage
of not requiring a CLR change. Whenever you use someone else’s code you’re always taking a certain amount on
trust anyway, so arguably it’s not an awful risk. More about the services of System.ClassEnum
later…

The next piece of functionality is to have some members with overridden behaviour. The canonical example
of this is simple arithmetic operations – addition, subtraction, division and multiplication. The enumeration
contains a value for each operation, and has an Eval method to perform the operation. Here’s
what it would look like in C#:

public class enum ArithmeticOperation
{
    Addition
    {
        public override int Eval(int x, int y)
        {
            return x+y;
        }
    },
    
    Subtraction
    {
        public override int Eval(int x, int y)
        {
            return x-y;
        }
    },
    
    Multiplication
    {
        public override int Eval(int x, int y)
        {
            return x*y;
        }
    },
    
    Division
    {
        public override int Eval(int x, int y)
        {
            return x/y;
        }
    };
    
    public abstract int Eval(int x, int y);
}

Sometimes, you may wish to save a bit of space and specify the implementation of
a method as a delegate – especially if the method would otherwise be abstract (i.e.
there was no “common” implementation which most values would use). Here, C#’s
anonymous method syntax helps:

public class enum ArithmeticOperation
{    
    delegate int Int32Operation (int x, int y);
    
    Addition (delegate (int x, int y) { return x+y; }),
    Subtraction (delegate (int x, int y) { return x-y; }),
    Multiplication (delegate (int x, int y) { return x*y; }),
    Division (delegate (int x, int y) { return x/y; });
        
    Int32Operation op;
    
    ArithmeticOperation (Int32Operation op)
    {
        this.op = op;
    }
    
    public int Eval (int x, int y)
    {
        return op(x, y);
    }
}

That’s still a bit clumsy, of course – let’s try with lambda function syntax instead:

public class enum ArithmeticOperation
{    
    Addition ( (x,y) => x+y),
    Subtraction ( (x,y) => x-y),
    Multiplication ( (x,y) => x*y),
    Division ( (x,y) => x/y);
        
    Func<int, int> op;
    
    ArithmeticOperation (Func<int,int> op)
    {
        this.op = op;
    }
    
    public int Eval (int x, int y)
    {
        return op(x, y);
    }
}

Now we’re really cooking! Of course, some of the time you’ll be able to provide a single implementation for most values,
which only some values will want to override. Something like:

public class enum InputType
{
    Integer,
    String,
    Date
    {
        // Default implementation isn't quite good enough for us
        public override string Format(object o)
        {
            return ((DateTime)o).ToString("yyyyMMdd");
        }
    };
    
    // Default implementation of formatting
    public virtual string Format(object o)
    {
        return o.ToString();
    }
}

So far, this is all quite similar to Java’s enums in appearance. Java’s enums also come with an ordinal
(the position of declaration within the enum) automatically, but in my experience this is as much of a
pain as it is a blessing. In particular, as that ordinal can’t be specified in the source code, if you
have other code relying on specific values (e.g. to pass data across a web-service) you have to leave
bogus values in the list in order to keep the ordinals of the later values the same. Java also only
allows you to specify the constructors in “top-most” enum. This can occasionally be a nuisance. Let’s extend
the enum above to include DateTime and Time – both of which need the same kind of
“special” formatting. In Java, you’d have to override Format in three different places, like
this:

public class enum InputType
{
    Integer,
    String,
    DateTime
    {
        public override string Format(object o)
        {
            return ((System.DateTime)o).ToString("yyyyMMdd HH:mm:ss");
        }
    },
    Date
    {
        public override string Format(object o)
        {
            return ((System.DateTime)o).ToString("yyyyMMdd");
        }
    },
    Time
    {
        public override string Format(object o)
        {
            return ((System.DateTime)o).ToString("HH:mm:ss");
        }
    };
    
    public virtual string Format(object o)
    {
        return o.ToString();
    }
}

I would propose that enum values could reuse each other’s implementations, possibly
parameterising them via constructors. The above could be rewritten as:

public class enum InputType
{
    Integer,
    String,
    DateTime("yyyyMMdd HH:mm:ss")
    {
        string formatSpecifier;
        
        protected DateTime(string formatSpecifier)
        {
            this.formatSpecifier = formatSpecifier;
        }
        
        public override string Format(object o)
        {
            return ((System.DateTime)o).ToString(formatSpecifier);
        }
    },
    Date : DateTime("yyyyMMdd"),
    Time : DateTime("HH:mm:ss");
    
    public virtual string Format(object o)
    {
        return o.ToString();
    }
}

If Date wanted to further specialise the class (e.g. if another method needed overriding),
it could add implementation there too. Note that the DateTime constructor does not explicitly
call any constructor. In this case, an implicit call to the InputType constructor which took
only the name parameter would be made. Explicit calls to base class constructors could be included in the normal
way – the extra parameter would be entirely hidden from the source code. Only protected constructors could
be called by derived types in the normal way.

Switch

Switch statements would appear in exactly the same way they do now. (Possibly without the qualification (e.g.
case Time: instead of case InputType.Time:. The code is more readable without the
qualification, and is unambiguous, but it would be inconsistent with the current handling of switch cases
for “normal” enums.) The implementation would work a lot like strings – either using the equivalent of
a sequence of if statements or building a map behind the scenes. This is where keeping something
like Java’s ordinals would speed things up, but then I would at least want something like an attribute to be able to
specify the value in source code to avoid the problems described in Java earlier. Note that only reference
equality needs to be checked in any of these cases, as only one instance of any value would be created.

Static field initializers and static constructors

Java has restrictions on where you can use static fields in enums, because the static field initializers
are executed after the enum values have been created. Static fields are useful in a surprising number
of circumstances, mostly getting at an enum value dynamically by something other than name. The rules
for this would need to be considered carefully – sometimes it’s useful to have code which will be run
after the enums have all been set up; other times you want it beforehand (so you can use the static fields
during initialization, e.g. to add a value to a map).

Other features

Like Java, there could be an EnumSet<T> type which would be the equivalent of using
FlagsAttribute on normal enums. Indeed, the compiler could even generate operator overloads
to make this look nicer.

In Java, some enums with many values overriding many methods can end up being pretty large. In
C#, of course, we can use partial types to split the whole enum definition over several
files. (Some may object to this, others not – it would be available if you wanted it.)

Open questions

  • The potential abuse problem mentioned earlier
  • Serialization/deserialization would need to know to use the previously set up values
  • Should identifying values (like Java ordinals) be present, if only for switch performance?

I suspect there are other things I haven’t thought of, but with any luck this will be food for thought.

Deadlock detection – finally released

I’d hoped to be able to make this post a week ago, but adding extra unit tests, performance tests and documentation took longer than expected. (Doesn’t it always?)

I’ve now refactored the previous incarnation of SyncLock in my Miscellaneous Utility Library (snappy title, huh?) and added a new type of lock which can detect deadlocks (throwing an exception instead of entering the deadlock-prone state). There’s also a usage page explaining how to use the locks, and what the performance impact is. (Well, what it is on my box, anyway.) Any further suggestions now it’s concrete are welcome, of course.

Pedantry – how much is too much?

I’m a pedant, there’s no doubt about it. I’m particularly pedantic when it comes to terminology in computing discussions – at least where I see value in being precise about what is meant. So, when discussing static constructors in a mailing list thread recently, I’ve been very carefully distinguishing between a static constructor (which is a C# term) and a type initializer (which is a CLI term). This hasn’t been met terribly favourably by those who wish to use the term “static constructor” to mean both the .cctor member in a (compiled) type and the C# static constructor, despite them being slightly different in semantics and belonging to different domains. Now, I don’t wish to spill that discussion over onto my blog, but it has made me think about the general issue of pedantry when it comes to terminology.

Pedantry is rarely popular, but I believe it does bring value to a discussion, especially when some subtleties are involved. I generally assume a specification to be the authoritative source of information on terms related to the topic covered by the specification, as it’s a piece of common ground on which to base discussions. (The exception to this is if the spec is generally agreed to be incorrect in a particular regard.) If I talk about something being a variable and you understand “variable” in a completely different way to me, it’s a potential source of great confusion. I’m not pedantic to gain a feeling of superiority – I’m pedantic to try to make sure everyone’s effectively speaking the same language.

Of course, you don’t need to be absolutely precise all the time. If I were discussing an ASP.NET problem, for instance, I probably wouldn’t feel too bad about a sentence such as “x is now a string of length 5”. However, if I were discussing variables, reference types etc, I’d probably try to be more precise: “The value of x is now a reference to a string of length 5.” Writing (or reading) the second style for prolonged periods gets quite tedious, but I believe it’s important to be able to move into that mode when the need arises.

So, the question is: am I the only one who feels this way? I would expect most of the readers of this blog to be people who’ve read either my newsgroup posts, mailing list posts, or C# articles, so you probably have a fair idea of what I’m like. Do I go over the top, or do you find it useful? Is there a way of bringing precision to a discussion without irritating people (as I tend to, unfortunately)? Just to possibly remind you of things I’m often pedantic about, here’s a brief list of “pet peeves” which tend to involve people cutting fast and loose with terminology:

  • Value types “always being on the stack”
  • “Objects are passed by reference by default”
  • “C# supports two floating-point types: float and double.” (That one’s in the C# spec, unfortunately – decimal is also a floating point type.)
  • “I’m having trouble with ASCII characters above 127…” (along with its side-kick “I’m using extended ASCII”)
  • Volatility and atomicity being mixed up

Visual Studio vs Eclipse

I often see people in newsgroups saying how wonderful Visual Studio is, and they often claim it’s the “best IDE in the world”. Strangely enough, most go silent when I ask how many other IDEs they’ve used for a significant amount of time. I’m not going to make any claims as to which IDE is “the best” – I haven’t used all the IDEs available, and I know full well that one (IDEA) is often regarded as superior to Eclipse. However, here are a few reasons I prefer Eclipse to Visual Studio (even bearing in mind VS 2005, which is a great improvement). Visual Studio has much more of a focus on designers (which I don’t
tend to use, for reasons given elsewhere) and much less of a focus on making actual coding as easy as possible.

Note that this isn’t a comparison of Java and C# (although those are the languages I use in Eclipse and VS respectively). For the most part, I believe C# is an improvement on Java, and the .NET framework is an improvement on the Java standard library. It’s just a shame the tools aren’t as good. For reference, I’m comparing VS2005 and Eclipse 3.1.1. There are new features being introduced to Eclipse all the time (as I write, 3.2M4 is out, with some nice looking things) and obviously MS is working on improving VS as well. So, without further ado (and in no particular order):

Open Type/Resource

When I hit Ctrl-Shift-T in Eclipse, an “Open Type” dialog comes up. I can then type in the name of any type (whether it’s my code, 3rd party library code, or the Java standard library code) and the type is opened. If the source is available (which it generally is – I’ve used very few closed source 3rd party Java components, and the source for the Java standard library is available) the source opens up; otherwise a list of members is displayed.

In large solutions, this is an enormous productivity gain. I regularly work with solutions with thousands of classes – remembering where each one is in VS is a bit of a nightmare. Non-Java resources can also be opened in the same way in Eclipse, using Ctrl-Shift-R instead. One neat feature is that Eclipse knows the Java naming conventions, and lets you type just the initial letters instead of the type name itself. (You only ever need to type as much as you want in order to find the type you’re after anyway, of course.) So for example, if I type “NPE”, I’m offered NullPointerException and NoPermissionException.

Note that this isn’t the same as the “Find Symbol” search offered by VS 2005. Instead, it’s a live updating search – as you type, the list is updated. This is very handy if you can’t remember whether it’s ArgumentNullException or NullArgumentException and the like – it’s very fast to experiment with.

There’s good news here: Visual Studio users have a saviour in the form of a free add-in called DPack, by USysWare. This offers dialogs
for opening types, members (like the Outline dialog, Ctrl-O, in Eclipse), and files. I’ve only just heard about it, and haven’t tried it on a large solution yet, but I have high hopes for it.

Sensible overload intellisense

(I’m using the word intellisense for what Eclipse calls Code Assist – I’m sure you know what I mean.) For some reason, although Visual Studio is perfectly capable of displaying the choice of multiple methods within a drop-down list, when it comes to overloads it prefers a spinner. Here’s what you get if you type sb.Append( into Visual Studio, where sb is a StringBuilder
variable:

Here’s what happens if you do the equivalent in Eclipse:

Look ma, I can see more than one option at once!

Organise imports

For those of you who aren’t Java programmers, import statements are the equivalent to using directives in C# – they basically import a type or namespace so that it can be used without the namespace being specified. In Visual Studio, you either have to manually type the using directives in (which can be a distraction, as you have to go to the top of the file and then back to where you were) or (with 2005) you can hit Shift-Alt-F10 after typing the name ofthe type, and it will give you the option of adding a using statement, or filling in the namespace for you. Now, as far as I’m aware, you have to do that manually for each type. With Eclipse, I can write a load of code which won’t currently compile, then hit Ctrl-Shift-O and the imports are added. I’m only prompted if there are multiple types available from different namespaces with the same name. Not only that, but I can get intellisense for the type name while I’m typing it even before I’ve added the import – and picking the type adds the import automatically. In addition, organise imports removes import statements which aren’t needed – so if you’ve added something but then gone back and removed it, you don’t have misleading/distracting lines at the top of your file. A feature which isn’t relevant to C# anyway but which is quite neat is that Eclipse allows you to specify how many individual type imports you want before it imports the whole package (e.g. import java.util.*). This allows people to code in whatever style they want, and still get
plenty of assistance from Eclipse.

Great JUnit integration

I confess I’ve barely tried the unit testing available in Team System, but it seems to be a bit of a pain in the neck to use. In Eclipse, having written a test class, I can launch it with a simple (okay, a slightly complicated – you learn to be a bit of a spider) key combination. Similarly I can select a package or a whole source directory and run all the unit tests within it. Oh, and it’s got a red/green bar, unlike Team System (from what I’ve seen). It may sound like a trivial thing, but having a big red/green bar in your face is a great motivator in test driven development. Numbers take more time to process – and really, the most important thing you need to know is whether all the tests have passed or not. Now, Jamie Cansdale has done a great job with TestDriven.NET, and I’m hoping that he’ll integrate it with VS2005 even better, but Eclipse is still in the lead at this point for me. Of course, it helps that it just comes with all this stuff, without extra downloads (although there are plenty of plugins available). Oh, and just in case anyone at Microsoft thinks I’ve forgotten: no, unit testing still doesn’t belong in just Team System. It should be in the Express editions, in my view…

Better refactoring

MS has made no secret of the fact that it doesn’t have many refactorings available out of the box. Apparently they’re hoping 3rd parties will add their own – and I’m sure they will, at a cost. It’s a shame that you have to buy two products in 2005 before you can get the same level of refactoring that has been available in Eclipse (and other IDEs) for years. (I know I was using Eclipse in 2001, and possibly earlier.)

Not only does Eclipse have rather more refactorings available, but they’re smarter, too. Here’s some sample code in C#:

public void DoSomething()
{
    string x = "Hello";
    byte[] b = Encoding.UTF8.GetBytes(x);
    byte[] firstHalf = new byte[b.Length / 2];
    Array.Copy(b, firstHalf, firstHalf.Length);
    Console.WriteLine(firstHalf[0]);
}

public void DoSomethingElse()
{
    string x = "Hello there";
    byte[] b = Encoding.UTF8.GetBytes(x);
    byte[] firstHalf = new byte[b.Length / 2];
    Array.Copy(b, firstHalf, firstHalf.Length);
    Console.WriteLine(firstHalf[0]);
}

If I select the last middle lines of the first method, and use the ExtractMethod refactoring, here’s what I get:

public void DoSomething()
{
    string x = "Hello";
    byte[] firstHalf = GetFirstHalf(x);
    Console.WriteLine(firstHalf[0]);
}

private static byte[] GetFirstHalf(string x)
{
    byte[] b = Encoding.UTF8.GetBytes(x);
    byte[] firstHalf = new byte[b.Length / 2];
    Array.Copy(b, firstHalf, firstHalf.Length);
    return firstHalf;
}

public void DoSomethingElse()
{
    string x = "Hello there";
    byte[] b = Encoding.UTF8.GetBytes(x);
    byte[] firstHalf = new byte[b.Length / 2];
    Array.Copy(b, firstHalf, firstHalf.Length);
    Console.WriteLine(firstHalf[0]);
}

Note that second method is left entirely alone. In Eclipse, if I have some similar Java code:

public void doSomething() throws UnsupportedEncodingException
{
    String x = "hello";        
    byte[] b = x.getBytes("UTF-8");
    byte[] firstHalf = new byte[b.length/2];
    System.arraycopy(b, 0, firstHalf, 0, firstHalf.length);
    System.out.println (firstHalf[0]);
}

public void doSomethingElse() throws UnsupportedEncodingException
{
    String y = "hello there";        
    byte[] bytes = y.getBytes("UTF-8");
    byte[] firstHalfOfArray = new byte[bytes.length/2];
    System.arraycopy(bytes, 0, firstHalfOfArray, 0, firstHalfOfArray.length);
    System.out.println (firstHalfOfArray[0]);
}

and again select Extract Method, then the dialog not only gives me rather more options, but one of them is whether to replace the duplicate code snippet elsewhere (along with a preview). Here’s the result:

public void doSomething() throws UnsupportedEncodingException
{
    String x = "hello";        
    byte[] firstHalf = getFirstHalf(x);
    System.out.println (firstHalf[0]);
}

private byte[] getFirstHalf(String x) throws UnsupportedEncodingException
{
    byte[] b = x.getBytes("UTF-8");
    byte[] firstHalf = new byte[b.length/2];
    System.arraycopy(b, 0, firstHalf, 0, firstHalf.length);
    return firstHalf;
}

public void doSomethingElse() throws UnsupportedEncodingException
{
    String y = "hello there";        
    byte[] firstHalfOfArray = getFirstHalf(y);
    System.out.println (firstHalfOfArray[0]);
}

Note the change to doSomethingElse. I’d even tried to be nasty to Eclipse, making the variable names different in the second method. It still does the business.

Navigational Hyperlinks

If I hold down Ctrl and hover over something in Eclipse (e.g. a variable, method or type name), it becomes a hyperlink. Click on the link, and it takes you to the declaration. Much simpler than right-clicking and hunting for “Go to definition”. Mind you, even that much
isn’t necessary in Eclipse with the Declaration view. If you leave your cursor in a variable, method or type name for a second, the Declaration view shows the appropriate code – the line
declaring the variable, the code for the method, or the code for the whole type. Very handy if you just want to check something quickly, without even changing which editor you’re using. (For those of you who haven’t used Eclipse, a view is a window like the Output window in VS.NET. Pretty much any window which isn’t an editor or a dialog is a view.)

Update! VS 2005 has these features too!
F12 is used to go to a definition (there may be a shortcut key in Eclipse as well to avoid having to use the mouse – I’m not sure).
VS 2005 also has the Code Definition window which is pretty much identical to the Declaration view. (Thanks for the tips, guys :)

Better SourceSafe integration

The source control integration in Eclipse is generally pretty well thought through, but what often amuses me is that it’s easier to use Visual SourceSafe (if you really have to – if you have a choice, avoid it) through Eclipse (using the free plug-in) than through Visual Studio. The whole binding business is much more easily set up. It’s a bit more
manual, but much harder to get wrong.

Structural differences

IDEs understand code – so why do most of them not allow you to see differences in code terms? Eclipse does. I can ask it to compare two files, or compare my workspace version with the previous (or any other) version in source control, and it shows me not just the textual
differences but the differences in terms of code – which methods have been changed, which have been added, which have been removed. Also, when going through the differences, it shows blocks at a time and then what’s changed within the block – i.e. down to individual words, not just lines. This is very handy when comparing resources in foreign languages!

Compile on save

The incremental Java compiler in Eclipse is fast. Very, very fast. And it compiles in the background now, too – but even when it didn’t, it rarely caused any bother. That’s why it’s perfectly acceptable for it to compile (by default – you can change it of course) whenever you save. C# compiles a lot faster than C/C++, but I still have to wait a little while for a build to finish, which means that I don’t do it as often as I save in Eclipse. That in turn means I see some problems later than I would otherwise.

Combined file and class browser

The package explorer in Eclipse is aware that Java files contain classes. So it makes sense to allow you to expand a file to see the types within it:

That’s it – for now…

There are plenty of other features I’d like to mention, but I’ll leave it there just for now. Expect this blog entry to grow over time…

New (to me) threading paradigms

In the last couple of days, I’ve been reading up on CSPs (Communicating Sequential Processes) and the Microsoft Research project CCR (Concurrency and Coordination Runtime). I suspect that the latter is really a new look at the former, but I don’t have enough experience with either of them to tell. Now, I know a number of my readers are smart folks who have probably lived and breathed these things for a while – so, is my hunch right, or are they fundamentally different models?

A few links for further reading:

System.Random (and java.util.Random)

This is as much a “before you forget about it” post as anything else.

Both Java and .NET have Random classes, which allow you to get random numbers within a certain range etc. Unless you specify otherwise, both are seeded with the current time. Neither class claims to be thread-safe. This presents a problem – typically you effectively just want one source of random numbers, but you want to be able to access it from multiple threads. You certainly don’t want to create a new instance of the Random class every time you want a random number – due to the granularity of the system clock, that commonly gives repeated sequences of random numbers (i.e. multiple instances are created with the same seed, so each instance gives the same sequence).

I suggest that very few people really need to specify seeds – which means they don’t really need instance methods in the first place. A class with static methods (matching the interface of Random) would be perfectly adequate. This could be implemented using a single Random instance and locking to get thread safety, but a slightly more elegant (or at least more interesting) way would be to use thread-local static variables. In other words, each thread gets its own instance of Random. Now, that introduces the problem of which seed to use for each of these instances. That’s pretty easily solved though – either you take some combination of the thread ID and the current time, or you create a new instance of Random the first time any thread accesses the class, and use that Random as the source of seeds for future Randoms. The only time locking is needed is to access that Random, which occurs once per thread.

This does, of course, break my “keep it as simple as possible” rule – the simplest solution would certainly be to lock each time. In this case though, as this will end up as a library class which may well be used by many threads simultaneously in situations where a lot of random numbers are being generated, I think it’s worth the extra effort. I’ll probably write this up as an article when I’ve written the tests and implementation…

Code formatter online

I’ve finally got round to doing it… the code I use for posting code for articles etc has now been transformed into a small ASP.NET app. It’s based on a VB.NET article. I converted it from VB.NET to C# using Instant C# (which worked very well – just a few gotchas, far fewer than last time I tried it) and then refactored it into a more object-oriented and cleanly layered structure. There’s now a WinForms application, and a separate class library, which the ASP.NET app uses.

If you want to use the results yourself, you’ll need the stylesheet I use. Unfortunately, between this blog, my home page, and the home for the application, I’m starting to get far too many copies floating around – I may need to rationalise at some stage, as making a change is becoming painful. Anyway, just reference the stylesheet in your page header, cut and paste whatever the app provides for you (between the textbox and the sample output) and you’re away.

The site is hosted by AspSpider.NET – free ASP.NET hosting. I only signed up with them yesterday, and everything seems to work pretty seamlessly, so it seems reasonable to acknowledge them in this post :)

The code can still be made a lot prettier, but it’s getting there. I was pleased with the ASP.NET side of things – obviously (being me) I did it all in a plain text editor, and the resulting .aspx page is 29 lines, with the code-behind weighing in at 60 lines. Nice.

Future plans for it:

  • A drop down list of languages (easy) (done, 17th Nov 2005)
  • A radio-button for the format type (css, html – easy)
  • Adding Java to the list of languages (hopefully fairly easy) (done, 17th Nov 2005)
  • Giving the code back to the Darren Neimke

CLI spec mistake with unboxing and enums

When looking over someone’s test code the other day, I happened to notice he was unboxing a boxed enum to an int. I was mildly surprised that he was able to do so – I thought you could only ever unbox to the exact value type that was “in the box”. Naturally, I consulted the spec. The C# spec is relatively woolly on the subject, unfortunately, but the CLI spec (partition three, end of chapter 4 for those who wish to look it up) is very clear. Here’s what it states under the Exceptions section, which is the interesting part – obj is the value to unbox, valuetype is the type we’re tring to unbox to:

InvalidCastException is thrown if obj is not a boxed valuetype (or if obj is a boxed enum and valuetype is not its underlying type)

That’s from the first edition of the spec. The third edition (still under consideration for approval by ISO/IEC) has this:

System.InvalidCastException is thrown if obj is not a boxed valuetype, or if obj is a boxed enum and valuetype is not its underlying type.

Seems harmless enough, right? Well, consider a situation where you have two enums, FirstEnum and SecondEnum. Then consider this (the code is in C#, but the generated IL is a direct translation – in particular, the types used for unboxing are preserved):

// Keep declarations out of the way to focus on the conversions.
object o;
int i;
FirstEnum x;
SecondEnum y;

o = 1; // The value of o is a boxed System.Int32
i = (int) o; // Conversion 1
x = (FirstEnum) o; // Conversion 2
y = (SecondEnum) o; // Conversion 3

o = (FirstEnum)1; // The value of o is a boxed FirstEnum
i = (int) o; // Conversion 4
x = (FirstEnum) o; // Conversion 5
y = (SecondEnum) o; // Conversion 6

Now, which of those versions should succeed? Reading absolutely literally, only conversion 1 should work. The others should all throw InvalidCastException. In all but conversions 1 and 4, the first part of the “or” clause in the spec is true (i.e. we’re trying to unbox to a different type) and in conversion 5, the second part of the “or” clause is true (the value is a boxed enum, and the type we’re trying to unbox it to isn’t the underlying type – it’s the real type!).

I know that’s reading the spec very literally, rather than taking the obviously intended meaning – but specifications should be precise documents. In fact, I’m not sure the intended meaning is so obvious anyway. Clearly conversions 1 and 5 should work (an “exact match” should always be valid) but what about 4? Should I be able to unbox an enum to an int? The way the spec is worded suggests that probably I should. What about the other way round (conversions 2 and 3), unboxing an int to an arbitrary enum which has int as its underlying type? Not so sure about that. As for conversion 6, unboxing one enum to a completely different one (which happens to share the same underlying type) – I think I’d actually rather that failed.

So, what happens? Under the current .NET implementations, all the conversions succeed. That pretty much means that’s the way the behaviour is going to have to stay, meaning I won’t be able to get my wish about conversion 6. Still, never mind – what’s important is that the spec matches reality. I believe it’s very hard to word this in the “single sentence” style they’ve tried for. I think I’d say:

System.InvalidCastException is thrown if none of the following valid conversions are applicable:

  • obj is a boxed valuetype (covers 1 and 5)
  • valuetype is an enum, and obj is a boxed value of the underlying type of valuetype (covers 2 and 3)
  • obj is a boxed enum with underlying type valuetype (covers 4)
  • valuetype is an enum, and obj is a boxed value of an enum with the same underlying type as valuetype (covers 5
    and 6)

Book idea

Having just glanced at the clock, now is the ideal time to post about an idea I had a little while ago – a book (or blog, or something) about C# (or maybe C# and Java) which I’d only write between midnight and one in the morning.

It would contain only those things which seemed like really good ideas at the time – but which might seem insane at other times. Most of these ideas are probably useless, but may contain a germ of interest. While I don’t always have those ideas between midnight and one, that’s the time of night when they seem most potent, and when I’d be most likely to be ready to write enthusiastically about them. The coding equivalent of “beer goggles” if you will.

A couple ideas I’ve had which would probably qualify:

Extension interfaces

If C# 3.0 is going to allow us to pretend to add methods to classes, which shouldn’t it allow us to pretend that classes implement interfaces they don’t? My original reason for wanting this is to get rid of some of the ugliness in the suggesting new XML APIs: there’s a method which takes an array of objects, even though only a handful of types are catered for. Unfortunately, those types don’t have an interface in common, so all the checking has to be done at runtime. If you could pretend that they all implement the same interface, just for the purposes of the API, you could declare the method as taking an array of the interface type. Of course, this is much less straightforward than converting what looks like an instance method call into a static method call…

Conditional returns

This came up when implementing Equals for several types in quick succession. All of them followed a very similar pattern, and there were similar things needed at the start of each implementation – simple checks for nullity, reference identity etc. It would be interesting to have a sort of “nullable return” for methods which had a non-nullable value type return type – I could write return? expression; where the expression was a nullable form of the return type, and it would only return if the expression was non-null. There are bits of this which appeal, and bits which seem horrible – but the main problem I have with it is that I suspect would rarely use it outside Equals implementations. (If this isn’t a clear enough description, I’m happy to write an example – just not right now.)

Corner cases in Java and C#

Every language has a few interesting corner cases – bits of surprising behaviour
which can catch you out if you’re unlucky. I’m not talking about the kind of thing
that all developers should really be aware of – the inefficiencies of repeatedly
concatenating strings, etc. I’m talking about things which you would never suspect
until you bump into them. Both C#/.NET and Java have some oddities in this respect,
and as most are understandable even to a developer who is used to the other, I thought
I’d lump them together.

Interned boxing – Java 1.5

Java 1.5 introduced autoboxing of primitive types – something .NET has had
from the start. In Java, however, there’s a slight difference – the boxed
types have been available for a long time, and are proper named reference
types just as you’d write elsewhere. In this example, we’ll look at
int boxing to java.lang.Integer. What would you
expect the results of the following operation to be?

Object x = 5;
Object y = 5;
boolean equality = (x==y);

Personally, I’d expect the answer to be false. We’re testing for reference equality
here, after all – and when you box two values, they’ll end up in different boxes,
even if the values are the same, right? Wrong. Java 1.5 (or rather, Sun’s current
implementation of Java 1.5) has a sort of cache of interned values between -128 and
127 inclusive. The language specification explicitly states that programmers shouldn’t
rely on two boxed values of the same original value being different (or being the
same, of course). Goodness only knows whether or not this actually yields performance
improvements in real life, but it can certainly cause confusion. I only ran into it
when I had a unit test which incorrectly asserted reference equality rather than
value equality between two boxed values. The tests worked for ages, until I added
something which took the value I needed to test against above 127.

Lazy initialisation and the static constructor – C#

One of the things which is sometimes important about the pattern I usually use when
implementing a singleton
is that it’s only initialised when it’s first used – or is it? After a newsgroup
question asked why the supposedly lazy pattern wasn’t working, I investigated a little,
finding out that there’s a big difference between using an initialiser directly on
the static field declaration, and creating a static constructor which assigns the value.
Full details on my beforefieldinit
page.

The old new object – .NET

I always believed that using new with a reference type would give me
a reference to a brand new object. Not quite so – the overload for the String
constructor which takes a char[] as its single parameter will return
String.Empty if you pass it an empty array. Strange but true.

When is == not reflexive? – .NET

Floating point numbers have been
the cause of many headaches over the years. It’s relatively well known that “not a number” is not equal
to itself (i.e. if x=double.NaN, then x==x is false).

It’s slightly more surprising when two values which look like they really, really should be equal just
aren’t. Here are a couple of sample programs:

using System;
public class Oddity1
{
    public static void Main()
    {
        double two = double.Parse("2");
        double a = double.Epsilon/two;
        double b = 0;
        Console.WriteLine(a==b);
        Console.WriteLine(Math.Abs(b-a) < double.Epsilon);
    }
}

On my computer, the above (compiled and run from the command line) prints out True twice.
If you comment out the last line, however, it prints False – but only under .NET 1.1.
Here’s another:

using System;

class Oddity2
{
    static float member;

    static void Main()
    {
        member = Calc();
        float local = Calc();
        Console.WriteLine(local==member);
        member = local;
    }

    static float Calc()
    {
        float f1 = 2.82323f;
        float f2 = 2.3f;
        return f1*f2;
    }
}

This time it prints out True until you comment out the last
line, which changes the result to False. This occurs on both .NET 1.1 and 2.0.

The reason for these problems is really the same – it’s a case of when the JIT decides to
truncate the result down to the right number of bits. Most CPUs work on 80-bit floating point
values natively, and provide ways of converting to and from 32 and 64 bit values. Now, if you
compare a value which has been calculated in 80 bits without truncation with a value which has
been calculated in 80 bits, truncated to 32 or 64, and then expanded to 80 again, you can run
into problems. The act of commenting or uncommenting the extra lines in the above changes what
the JIT is allowed to do at what point, hence the change in behaviour. Hopefully this will
persuade you that comparing floating point values directly isn’t a good idea, even in cases
which look safe.

That’s all I can think of for the moment, but I’ll blog some more examples as and when I see/remember
them. If you enjoy this kind of thing, you’d probably like
Java Puzzlers
– whether or not you use Java itself. (A lot of the puzzles there map directly to C#, and even those which
don’t are worth looking at just for getting into the mindset which spots that kind of thing.)