Can I Use Typedef’s in C#?
Posted by gregd1024 on February 15, 2008
When moving from C++ to C#, the following question often arises: does C# support typedef’s? Unfortunately, no. However, you can get pretty close. Consider this code:
using GLenum = System.UInt32;
The “using GLenum” statement makes the symbol “GLenum” equivalent to a “System.UInt32” name. Now you can use “GLenum” to declare identifiers instead of “UInt32.” In this way, it’s acting exactly like a C or C++ typedef. What’s actually happening is that you’re creating a C# alias – a mechanism which allows the renaming of a class, struct, or namespace. While this may seem pretty flexible, consider what happens when you try the following:
using GLfloat = float; // ERROR!
This line results in a compile error because “float” is a keyword. Why weren’t C# aliases built to support this as well? When you consider the original purpose of aliases it kind of makes sense. They were meant to save the programmer from lots of typing by providing a mechanism to shorten long qualifiers. We all know some namespaces and classes in C# are much longer than what you would typically see in a C++ program, so providing renaming support was practically a necessity. But do you really think a lot of programmers are going to shorten “float” or “int”? So when I said you can “get pretty close” to a C++ typedef, I was specifically referring to limitations such as this.
Another big limitation is that aliases are limited in scope. Only the namespace in which they’re declared can see them and their scope cannot cross multiple source files. The last part is severely limiting – it forces you to include the same declaration in every file. At least it’s better than nothing.