-->

Why are the aliases for string and object in lower

2020-06-18 09:28发布

问题:

Here are a list of aliases in C# (compliments of What is the difference between String and string in C#?):

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

I can see bool through char being lowercase aliases, because they are primitive types.

Why are object and string not capitalized, since they are complex types? Is this an oversight by the developers, or is there a necessary reason for them to be lowercase? Or is this an opinionated question?

You end up with things like string.Format() instead of String.Format(), which just look funky and make me think string is a variable.

回答1:

In C#, there are no "primitive types" and "complex types". There are classes and structs, (reference types and value types, respectively) among others. Both can include methods (e.g. char.IsDigit('a')). So your objections aren't really valid. But there is still the question: why?

I'm not sure if there's a good source for this, but I think the lowercase aliases are done to match the other C# keywords, which are themselves modeled on C/C++ keywords.



回答2:

Because all keywords (reserved identifiers) are lowercase.



回答3:

Regarding your last comment:

You end up with things like string.Format() instead of String.Format(), which just look funky and make me think string is a variable.

With C# 6, this becomes a moot point as you can do:

using static System.String;

...
var x = Format(...);

Or going further, you can do away with string.Format altogether and use $ instead.



回答4:

Answer is simple. If you want to use it like a class use String, if you want to use it like a keyword use string. Developers wanted to make us feel like we are using a primitive type. Because in C# nothing is primitive.