Skip Navigation Links

Why didn't someone tell me C# has typedef?

Categories

What do you do if you want a mapping between a string and a guid?

I reached for Dictionary<string, guid>. Job done. Strongly typed goodness.

But it's a bit ugly, isn't it? I need to use the generic parameters everywhere I want to use the type, so if I suddenly decide I want to use a structure instead of a guid, there's a lot of places to change.

If I want to abstract my code away from all of this implementation detail, I can create a derived class:

class SectionMapping : Dictionary<string, guid>
{
}

Which feels a bit klunky - empty classes are not the nicest of things.

So today's bright idea was to use a nice little trick with using:

using CategoryMapping = System.Collections.Generics.Dictionary<string, System.Guid>

And I can now use CategoryMapping wherever I had been using the Dictionary before.

The downside is that this is not a new type, like the SectionMapping class is - it's just an alias. In other words, I can use CategoryMapping and Dictionary<string, guid> interchangeably. If I create another "using" alias for, say, GroupMapping, then I can use an instance of CategoryMapping wherever I use GroupMapping. Contrast this with classes. If I define CategoryMapping and GroupMapping as empty classes that derive from Dictionary<string, guid>, they have the same interface, but the compiler views them as very different types.

Oh and it's only scoped to the C# file in which it's declared.

posted 7/19/2007 10:42:42 AM

 

Comments:

There are no comments to display for this post.

 

Name:  
Url (optional):  
Subject:  
Comment:  

Enter Captcha Validation:
(If you cannot read the Captcha image, press "Reset Image" to generate a new one)