Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# deriving from int32

Tags:

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?

like image 585
second Avatar asked May 11 '09 22:05

second


1 Answers

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 
like image 69
LukeH Avatar answered Sep 18 '22 13:09

LukeH