Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef in C# across several source files

Tags:

c#

I am writing a C wrapper an would like to use a typedef aquivalent to define some types which should be valid in quite a lot of source files. Those "types" are just different aliases to [u]int16/32/64_t, but are useful to distinguish function parameters.

One could use using MyId=System.Int32;, but this needs to be redeclared in every file as far as I see... Is there a better way?

like image 405
Danvil Avatar asked Oct 14 '22 06:10

Danvil


1 Answers

One alternate approach is to use a struct with implicit conversion to the underlying type.

public struct MyHandle
{
    private int _handle;

    internal MyHandle(int handle)
    {
        _handle = handle;
    }

    public static implicit operator int(MyHandle handle)
    {
        return handle._handle;
    }
}

Your internal code can still use it as the underlying type (int in this case) via the implicit conversion, but you expose it as a strong type to the user. Your user can also see the int value, though it's effectively meaningless to them. They can't directly cast an int to your Handle type, as the constructor is internal to your assembly and you don't provide a conversion operator for the other direction.

like image 200
Dan Bryant Avatar answered Nov 15 '22 05:11

Dan Bryant