Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a Type Alias in C# across multiple files

Tags:

c#

typedef

using

In C++, it's easy to write something along the lines of:

#ifdef FAST
typedef Real float;
#endif

#ifdef SLOW
typedef Real double;
#endif

#ifdef SLOWER
typedef Real quad;
#endif

In some common header file so I could simply write one version of code and #define the appropriate version to get different binaries.

I know in C# you can do something similar along the lines of:

using Real = double;

So that you can get the similar semantics to typedefs. But is it possible to do something similar to the C++ code above that I wouldn't have to write in every single file?

like image 441
Mike Bailey Avatar asked Jan 21 '11 22:01

Mike Bailey


1 Answers

Not if you want it to use the inbuilt IL operators - you would have to do it per-file. However, if you don't need that (I suspect you do) you could encapsulate it in a struct:

public struct Real {
     private readonly REAL_TYPE value;
     public(REAL_TYPE value) { this.value = value; }
     // TODO add lots of operators (add, multiply. etc) here...
}

(where REAL_TYPE is a using alias in the single file that declares Real)

For my money, not worth it. And the use if the static operators will be relatively slower that direct IL operations that you would get if it was in-situ.

like image 170
Marc Gravell Avatar answered Sep 24 '22 18:09

Marc Gravell