0

I want to create a type that is basically equivalent to System.Single, but with a subset of features. The reason for this is I have algorithms that emit timestamps in System.Single and I want to add extension methods to work with the results.

It would be inappropriate to add Method(this float a) as invalid values could be passed in.

I looked at the System.Single source code here. However, I don't understand why there's no constructor or setter of any sort. I checked a few of the other base value types and none of them have any visible method of setting the value.

How is this possible?

The reason I ask is I want my new type to be operable in the same way as the base types, so I want to create a type with the same behavior.

IamIC
  • 17,747
  • 20
  • 91
  • 154
  • System.Single being a "value type" *is* a value. Usually and for good reasons value types don't have setters; see e.g. https://stackoverflow.com/questions/441309/why-are-mutable-structs-evil – Klaus Gütter Apr 09 '20 at 13:21
  • Alright, but how do I create one? Defining a struct with no setter doesn't enable one to state `MyStruct x = 3`. The compiler has no idea what to set. – IamIC Apr 09 '20 at 13:29
  • 1
    If there is an implicit conversion operator like `public static explicit operator MyStruct(float f) => new MyStruct { _value = f };`, your code should work. – Klaus Gütter Apr 09 '20 at 13:33
  • @KlausGütter Though your code shows an explicit conversion operator, not an implicit one. – ckuri Apr 09 '20 at 19:33
  • I made it `implicit` and it works fine. I don't understand how the .Net source code works without one, though. – IamIC Apr 09 '20 at 19:41
  • @ckuri Right you are - thanks for correcting – Klaus Gütter Apr 10 '20 at 03:05
  • @IamIC Support for basic types is baked into the language – Klaus Gütter Apr 10 '20 at 03:07

0 Answers0