Danvil
Danvil

Reputation: 23031

Typedef in C# across several source files

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?

Upvotes: 5

Views: 745

Answers (2)

Dan Bryant
Dan Bryant

Reputation: 27515

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.

Upvotes: 4

Thomas
Thomas

Reputation: 64664

Since I'm assuming that you want to distinguish between a legitimate use of say UInt32 and your custom type, yes you would need to manually reference your alias everywhere you want it to be used.

Upvotes: 0

Related Questions