5

Is it possible to create an alias to existing types and use that alias through out the project?

For example, create

CustomerID = System.UInt32

and use CustomerID as a datatype?

Version : .NET Framework 4.0

(With the "using" keyword we would be able to create an alias, but it is not useful as it does not work across files.)

Any other ideas?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fr21
  • 1,746
  • 7
  • 26
  • 45
  • 1
    The reason why you have the use the `using` keyword on a namespace is because it is a very bad idea to create a global `using`. Imagine someone else using a `CustomerID` type in a different context and gets an unsigned integer back instead of their expected type. By restricting it to only a namespace, you prevent against this type of collision. – Daniel T. Feb 15 '11 at 20:22

2 Answers2

4

I believe the correct answer to this question is:

No, that's (unfortunately?) not possible. :(


Edit 1: However, you can (kind of) simulate this by making your own struct, and providing implicit conversions to/from the type you want. It's not exactly magical but it might work, depending on the situation.


Edit 2: I haven't ever used this feature before, but type forwarding might be helpful. It only forwards to another entire assembly, though, so it probably won't work for simple cases.

user541686
  • 205,094
  • 128
  • 528
  • 886
0

This doesn't seem possible. However, for which reason do you want to do this?

If your reason is readability, consider the following:

You can already use your identifiers to indicate it is e.g. a customerID. What you are essentially doing when trying to rename UInt32 to CustomerID is making it look like a new type. Only when a type needs additional behavior or values it is useful to consider it a 'new' type. If you ever developed in C++, you can appreciate the convention caused by not allowing this in C#. You know what to expect from a UInt32.

If your reason is preparing yourself for changes:

E.g. suppose after some time you decide you also want to support negative ID's. This should be solved by encapsulating this possible expected behavior in a new type. So no renaming is necessary.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161
  • 1
    Another reason is added type safety. Imagine you have a method `GetItem(uint customerID, uint itemID)`. Someone could accidentally put the arguments around the wrong way. However, if you use new types, such as `GetItem(CustomerID customerID, ItemID itemID)`, then mixing up the arguments will be a compile-time error. – porges Feb 15 '11 at 21:42