C# and typedef

Problem statement:
Typedef int to Tick and use it in three classes which are defined in three different files.
Files are: class1.cs, class2.cs and class3.cs

Solution 1:

Add this statement in all three files: class*.cs

using Tick = System.Int32

Disadvantage: If you choose to rename Tick to ClockTick, you need to change at three different places. You are violating the golden rule of one version of the truth.

Solution 2:

Derive out of the type you want to typedef’ed and use this instead.

Define a class Tick and derive it from Int32.

Disadvantage: This won’t work for non-user defined types like int, char, etc. It can work with ‘classes’.
For eg, this will work

public class TickList : List<int>

whereas this will not

public class Tick : System.Int32

Solution 3:

Create a wrapper around the type you want to be typedef’ed.

Disdvantage: It’s like using a saw to open a pack of biscuits. The solution is too much work compared to the problem. You need a typedef, and you should get a typedef and not a new class altogether!

public class Tick
{
int m_tick;
// Declare property here.
}

Conclusion:

C# does not support typedef, atleast not in the tradition C/C++ sense. Actually, this problem has an elegant solution in C/C++ (add this typedef in a .h file and include that file in all three source class*.c* files) because they have a concept of header files. C# removed header files and many useful features too.

Advertisements

2 thoughts on “C# and typedef

  1. Laurent says:

    Hi

    I have the following typedef in a C++ project and I would like to migrate to c#

    typedef int(*fooler)(int);

    fooler pfool = (fooler) GetProcAddress(hm,”f00ler”);

    How can I proceed?

    Thanks

    Laurent

  2. Ignatius says:

    Hi there. Is there any way to make that but with enum types?
    I´m writing my own DLL which uses an enum from other DLL (which is not mine).
    This 3rd-Part DLL has an enum that the user of my DLL also needs to use. The thing is that I dont want the user to know this 3rd-part enum because he doenst has to know which dlls i use inside mine.

    So I tried something like:

    using myEnum = ThirdPartEnum;

    but it doent seems to work.

    Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: