0

Is the reason same as in Why is Array.Length an int, and not an uint? I am asking because I will need to do some additional casting/validation in my code which will unnecessarily reduce readability and I think there should not be any issue with just casting Seconds to uint like below:

uint modulo = (uint)DateTime.Now.Second % triggerModuloSeconds;
sjanisz
  • 57
  • 8
  • Mainly because uint is not CLS-compliant. I rarely see people using uint for anything except when they are forced to do so, like for calling some third-party API. – tia Jul 27 '22 at 09:25
  • You know the reason why signed types are used but why do you need uint in your code at all? – Ralf Jul 27 '22 at 09:28
  • @Ralf if there are values that should not be negative then I do not see any reason to not make them unsigned (biggest benefit of this is for me at least is that You can skip additional validation). – sjanisz Jul 27 '22 at 09:39
  • 1
    Does this answer your question? [Why does .NET use int instead of uint in certain classes?](https://stackoverflow.com/questions/782629/why-does-net-use-int-instead-of-uint-in-certain-classes) – Charlieface Jul 27 '22 at 10:06
  • @Charlieface yes, though I am not completely satisfied as in my opinion we are losing small part of documentation – sjanisz Jul 27 '22 at 10:23

1 Answers1

1

Using int as the default data type tend to make programming easier, since it is large enough for most common use cases, and limits the risk someone makes a mistake with unsigned arithmetic. It will often have much greater range than actually needed, but that is fine, memory is cheap, and cpus may be optimized for accessing 32-bit chunks of data.

If you wanted the most precise datatype a byte would be most appropriate, but what would you gain from using that instead of an int? There might be a point if you have millions of values, but that would be rare to store something like seconds in that way.

As mentioned in the comments, unsigned types are not CLS compliant, so will limit compatibility with other languages that do not support unsigned types. And this would be needed for a type like DateTime.

You should also prefer to use specific types over primitives. For example using TimeSpan to represent, well, a span of time.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • Thanks for extensive response, in my case I am writing code handling triggers that occur every in example 5 minutes of current datetime, that is why I am using it. – sjanisz Jul 27 '22 at 10:19
  • @sjanisz to me that sounds exactly like a poor or incorrect usage. First of all `Seconds` is in the range [0, 59], you might want to use `.TotalSeconds`. Or add a modulu-extension method that takes two timespans. Or use a stopwatch that is reset for every cycle. Or just use a timer. – JonasH Jul 27 '22 at 11:02