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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With