Should I use int or Int32

前端 未结 30 2157
野性不改
野性不改 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:48

    You should not care in most programming languages, unless you need to write very specific mathematical functions, or code optimized for one specific architecture... Just make sure the size of the type is enough for you (use something bigger than an Int if you know you'll need more than 32-bits for example)

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

    ECMA-334:2006 C# Language Specification (p18):

    Each of the predefined types is shorthand for a system-provided type. For example, the keyword int refers to the struct System.Int32. As a matter of style, use of the keyword is favoured over use of the complete system type name.

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

    There is no difference between int and Int32, but as int is a language keyword many people prefer it stylistically (just as with string vs String).

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

    As already stated, int = Int32. To be safe, be sure to always use int.MinValue/int.MaxValue when implementing anything that cares about the data type boundaries. Suppose .NET decided that int would now be Int64, your code would be less dependent on the bounds.

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

    I always use the system types - e.g., Int32 instead of int. I adopted this practice after reading Applied .NET Framework Programming - author Jeffrey Richter makes a good case for using the full type names. Here are the two points that stuck with me:

    1. Type names can vary between .NET languages. For example, in C#, long maps to System.Int64 while in C++ with managed extensions, long maps to Int32. Since languages can be mixed-and-matched while using .NET, you can be sure that using the explicit class name will always be clearer, no matter the reader's preferred language.

    2. Many framework methods have type names as part of their method names:

      BinaryReader br = new BinaryReader( /* ... */ );
      float val = br.ReadSingle();     // OK, but it looks a little odd...
      Single val = br.ReadSingle();    // OK, and is easier to read
      
    0 讨论(0)
  • 2020-11-22 12:52

    It makes no difference in practice and in time you will adopt your own convention. I tend to use the keyword when assigning a type, and the class version when using static methods and such:

    int total = Int32.Parse("1009");
    
    0 讨论(0)
提交回复
热议问题