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

by matt 19. July 2007 09:42

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.

Tags:

Comments

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading



About the author

Something about the author

Calendar

<<July 2010>>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

RecentComments

Comment RSS

License

Creative Commons License
Except where otherwise noted, content on this site is by Matt Ellis and is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

©2010 Matt Ellis