In the "C# Coding Standard" by Juval Lowy available from www.idesign.net, the recomendation is made to use the C# predefined types instead of the aliases in the System
namespace, e.g.:
object
NOT Object
string
NOT String
int
NOT Int32
What is the benefit of this? How do they differ? I have followed this advise in my own coding but never knew how they differed.
In embedded systems and system programming, C is still the main language because you typically don't need objects there but more direct interface to hardward and low level things.
Is Learning C Worth It? Learning C is worth it. It is hard to avoid C because it is used to write OS kernels, databases, compilers, and many other applications. Knowledge of C will be required to debug or improve them.
I think using the 'blue' int
, string
, etc.. might be a little more intuitive to read. Otherwise, I use the class when calling a static method on it i.e. Int32.TryParse()
The main time they are unexpectedly different is when someone is stupid enough to call a type (or property /field/etc) String
(for example), since string
always refers to global::System.String
, where-as String
could be YourNamespace.String
.
The closest you can get to the C# alias is @string
, which tends to stick out like a sore thumb.
I prefer the C# aliases.
btw, here's a fun way to mess with anyone using dynamic
too much:
using dynamic = System.Object;
They don't really differ. Personally I use the aliases too, but Jeff Richter advocates the exact opposite. The generated code will be exactly the same. Use whichever you find most readable (and try to be consistent).
One thing most people agree on: when writing an API, use the type name rather than the alias, so:
int ReadInt32()
rather than
int ReadInt()
the int
part doesn't matter here - it's not part of the name, and can be displayed appropriately to any consumer using any language... but the method name should be language-neutral, which means using the type name.
One place where you have to use the alias is when specifying the underlying type for an enum:
enum Foo : byte // Valid
enum Foo : System.Byte // Invalid
In addition to what Jon said here is another difference.
var x = (Int32)-y; // Does not compile.
var x = (int)-y; // Negates the value of y and casts as an int.
This is because of a grammar disambiguation rule defined in §7.6.6 of the C# Programming Language specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With