Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

vb.net

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)?

like image 834
Adrian Godong Avatar asked May 26 '09 16:05

Adrian Godong


4 Answers

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.

like image 153
Reed Copsey Avatar answered Nov 24 '22 07:11

Reed Copsey


The language types (e.g. 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 :)

like image 33
Binary Worrier Avatar answered Nov 24 '22 06:11

Binary Worrier


The only time I would ever explicitly use "System.XYZ" in preference to a built-in type keyword is when I need an integer type of very specific size, and I want that to be clear to anyone reading my code (e.g. I might use Int32 instead of int if the integer in question is actually 4 8-bit fields packed together.)

like image 36
mqp Avatar answered Nov 24 '22 08:11

mqp


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.

like image 25
Daniel Brückner Avatar answered Nov 24 '22 07:11

Daniel Brückner