i have several classes with members called 'Id'. Originally i wanted to store these as ints, but i would like some layer of protection, to make sure i don't accidentally assign a room id to a person etc.
one solution would be typedef (using RoomId = System.Int32;) but then i need that line of code in all files using these. i would prefer e.g. a RoomId class derived from int32, but i can't figure out how to set it up to allow explicit conversion (for initilisation)
or should i do this in some other way?
You can't derive from Int32
, but you can specify implicit conversions, which might give you the behaviour you need:
public struct RoomId { private int _Value; public static implicit operator RoomId(int value) { return new RoomId { _Value = value }; } public static implicit operator int(RoomId value) { return value._Value; } } // ... RoomId id = 42; Console.WriteLine(id == 41); // False Console.WriteLine(id == 42); // True Console.WriteLine(id < 42); // False Console.WriteLine(id > 41); // True Console.WriteLine(id * 2); // 84
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