c#: difference between "System.Object" and "object"
In C#, is there any difference between using System.Object
in code rather than just object
, or System.String
rather than string
and so on? Or is it just a matter of style?
Is there a reason why one form is preferrable to the other?
Solution 1:
string
is an alias for global::System.String
. It's simply syntactic sugar. The two are exactly interchangable in almost all cases, and there'll be no difference in the compiled code.
Personally I use the aliases for variable names etc, but I use the CLR type names for names in APIs, for example:
public int ReadInt32() // Good, language-neutral
public int ReadInt() // Bad, assumes C# meaning of "int"
(Note that the return type isn't really a name - it's encoded as a type in the metadata, so there's no confusion there.)
The only places I know of where one can be used and the other can't (that I'm aware of) are:
-
nameof
prohibits the use of aliases - When specifying an enum base underlying type, only the aliases can be used
Solution 2:
The object type is an alias for System.Object. The object type is used and shown as a keyword. I think it has something to do with legacy, but that's just a wild guess.
Have a look at this MSDN page for all details.
I prefer the use of the lowercased versions, but for no special reasons. Just because the syntax highlighting is different on these "basic" types and I don't have to use the shift key when typing...
Solution 3:
One is an alias to the other. Its down to style.