简体   繁体   中英

Built-in types, when (not) to use?

C# and VB.NET comes with built in types that maps to the CLR types. Examples are: int (C#) and Integer (VB) maps to System.Int32, long (C#) and Long (VB) maps to System.Int64. What are the best practices for deciding when to use built in types or not to use them (using the System.* structs/classes instead)?

I nearly always use the built-in aliases, such as int/short/long. They are easier to read, and do not require you to import System or to type System.Int32 everywhere, etc.

The language clearly defines them, and gives them a specific meaning, so I do not see any harm. However, this is 100% a personal choice.

That being said - the one place where I do explicitly use Int32, Int16, etc., is if I'm dealing with binary storage or transfer, especially to or from a custom binary format. In this case, having the explicit bitsize of each member going into and out of the file makes the code more readable and understandable, IMO.

The language types (eg string, int, char) are simply Aliases for the CLR types (System.String, System.Int32, System.Char).

They are interchangeable, there is no need to prefer one over the other.

EDIT

The poster asked for some help in choosing between the two, very well.

Personally I tend to choose the C# language types (int, string, char etc), because they involve less typing - I suppose I'm just lazy :)

我唯一会优先使用“ System.XYZ"而不是内置类型关键字的情况是,当我需要一个非常特定大小的整数类型时,并且我希望所有阅读我的代码的人都可以清楚(例如,如果所讨论的整数实际上是4个8位字段打包在一起,请使用Int32而不是int 。)

I always use the System.* types because they look more consistent between other classes - upper case first letter and the same syntax highlighting. But that's just a personal preference and just an aesthetic issue.

Using "int" and "Int32" (and the others) are exactly same. Typicaly are used the keywords (int, Integer (vb.net), bool, etc...), because it is shorter and is highlited in IDE.

Rather than when to use or not use the language types versus explicit BCL class names, it is more important to know whether or not the type you intend to use is CLS Compliant.

Specifically, the unsigned integer types are not CLS compliant because there is no requirement that a language support unsigned integer math.

Other than this wrinkle... I would recommend whichever idiom is more in keeping with your organizations code practices. If you fully namespace your type references, then I would continue that pattern with the System.* namespace... (I would also recommend against that practice, though, as it adds reader load without attendant gain in clarity).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM