Should I use int or Int32

前端 未结 30 2129
野性不改
野性不改 2020-11-22 11:52

In C#, int and Int32 are the same thing, but I\'ve read a number of times that int is preferred over Int32 with no reason

相关标签:
30条回答
  • 2020-11-22 12:38

    You should not care. If size is a concern I would use byte, short, int, then long. The only reason you would use an int larger than int32 is if you need a number higher than 2147483647 or lower than -2147483648.

    Other than that I wouldn't care, there are plenty of other items to be concerned with.

    0 讨论(0)
  • 2020-11-22 12:38

    Using the Int32 type requires a namespace reference to System, or fully qualifying (System.Int32). I tend toward int, because it doesn't require a namespace import, therefore reducing the chance of namespace collision in some cases. When compiled to IL, there is no difference between the two.

    0 讨论(0)
  • 2020-11-22 12:40

    You shouldn't care. You should use int most of the time. It will help the porting of your program to a wider architecture in the future (currently int is an alias to System.Int32 but that could change). Only when the bit width of the variable matters (for instance: to control the layout in memory of a struct) you should use int32 and others (with the associated "using System;").

    0 讨论(0)
  • 2020-11-22 12:40

    Also consider Int16. If you need to store an Integer in memory in your application and you are concerned about the amount of memory used, then you could go with Int16 since it uses less memeory and has a smaller min/max range than Int32 (which is what int is.)

    0 讨论(0)
  • 2020-11-22 12:42

    I'd recommend using Microsoft's StyleCop.

    It is like FxCop, but for style-related issues. The default configuration matches Microsoft's internal style guides, but it can be customised for your project.

    It can take a bit to get used to, but it definitely makes your code nicer.

    You can include it in your build process to automatically check for violations.

    0 讨论(0)
  • 2020-11-22 12:46

    Use of Int or Int32 are the same Int is just sugar to simplify the code for the reader.

    Use the Nullable variant Int? or Int32? when you work with databases on fields containing null. That will save you from a lot of runtime issues.

    0 讨论(0)
提交回复
热议问题