When does it matter whether you use int versus Int32, or string versus String?

In C#, the keywords for built-in types are simply aliases for corresponding types in the System namespace.

Generally, it makes no difference whether you use a keyword (such as int ) or an identifier (such as Int32 ) to refer to a built-in type. But there's an exception to everything, so my question in two parts is:

  • When does C# require you to use, or not use, a keyword?
  • When does using a keyword instead of an identifier change the meaning of the program?

  • C# doesn't require you to use one or the other as they are equivalent. It is a personal preference and coding convention. So use the one that seems more readable to you and your team. Just one advice: be consistent: do not use an alias in half of your codebase and the full type name in the second half.


    string is an alias for the type System.String , and int is an alias for System.Int32 . Therefore, use to your preference.


    A using alias directive cannot use a keyword as the type name (but can use keywords in type argument lists):

    using Handle = int; // error
    using Handle = Int32; // OK
    using NullableHandle = Nullable<int>; // OK
    

    The underlying type of an enum must be specified using a keyword:

    enum E : int { } // OK
    enum E : Int32 { } // error
    

    The expressions (x)+y , (x)-y , and (x)*y are interpreted differently depending on whether x is a keyword or an identifier:

    (int)+y // cast +y (unary plus) to int
    (Int32)+y // add y to Int32; error if Int32 is not a variable
    (Int32)(+y) // cast +y to Int32
    
    (int)-y // cast -y (unary minus) to int
    (Int32)-y // subtract y from Int32; error if Int32 is not a variable
    (Int32)(-y) // cast -y to Int32
    
    (int)*y // cast *y (pointer indirection) to int
    (Int32)*y // multiply Int32 by y; error if Int32 is not a variable
    (Int32)(*y) // cast *y to Int32
    
    链接地址: http://www.djcxy.com/p/21200.html

    上一篇: 将两个列表结合在一起

    下一篇: 什么时候使用int还是Int32还是string与String?