views:

237

answers:

5

After I decided to implement my Int128 in C#, I thought it would be nice to make it look like other dotNet data types.. But I could not implement the following feature:

  • suffix initialization: such as 13L and 0.2D

Can I make my own suffix in C#?
And if I can not.. how can I initialize it?
i.e

Int128 a= ??
+16  A: 

No, you can't create your own form of literal in C#.

You could have an implicit conversion from int, long, uint and ulong, allowing:

Int128 a = 100;

but you wouldn't be able to specify values greater than ulong.MaxValue that way.

Having an implicit conversion from decimal would allow a larger range, but would be a bad idea because you would lose data for any value which wasn't just an integer.

Basically there's nothing which will allow a literal guaranteed-to-be-integer value greater than ulong.MaxValue - you could parse a string, but that's not really ideal. Alternatively you could create a constructor which took two ulongs, one for the bottom 64 bits and one for the top 64 bits.

Jon Skeet
+2  A: 

see this post http://stackoverflow.com/questions/227731/int128-in-net

Ioxp
+7  A: 

You cannot create your own suffix initializers - this is part of the language and baked into the compiler. If you write your own C# compiler, on the other hand, you can do whatever you want and extend it in whichever way you wish.

As for how you would initialize it - it depends on how you wrote it. If it is a class, you would need to initialize it with the new keyword, or write some implicit conversions to numeric types that have less precision.

As Jon noted, you will have no way to actually set it to a value larger than ulong.MaxValue without some string manipulation. You will also have to represent in internally in some form (string? A number of ulongs?) and make sure all conversions and operations work correctly (what about overflows?).

Oded
+1  A: 

No, you can't do suffix initialisation. That bit of cuteness will be available in the forthcoming C++ standard ... but I digress.

The most obvious choices are Int128(long hi, ulong lo) and Int128(string).

Marcelo Cantos
+1  A: 

You could look at the new BigInteger struct in 4.0 for tips on initialization. http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx

kicsit