A few days ago, I decided to start learning C#. So, I got a book and started reading and practicing with code. I was surprised when I saw that string
in C# is considered a primitive type.
But I was more surprised when I saw that string
, as well as all the other primitive types in C# have operations. I'm a Java developer and my understanding was that primitive data types don't have operations, only classes have. But in C#, the following is valid:
string name = "alex";
Console.WriteLine(name.ToUpper());
How is this possible? Are they really primitives? What am I missing here?
string
is not a primitive type in C#. It's one of two predefined (i.e., part of the language specification) reference types in C# (the other being object
). The primitive types in C# are Boolean
(bool
), Byte
(byte
), SByte
(sbyte
), Int16
(short
), UInt16
, Int32
(int
), UInt32 (uint
), Int64
(long
), UInt64 (ulong
), IntPtr
, UIntPtr
, Char
(char
), Double
(double
), and Single
(single
).
Note that the specification states "it is also possible to use structs and operator
overloading to implement new “primitive” types in the C# language" but that typeof(MyStruct).IsPrimitive
is false
if MyStruct
is a user-defined struct
.
I got a book and started reading and practicing with code. I was surprised when I saw that string in C# is considered a primitive type.
The book said this? Which book?
I'm a Java developer and my understanding was that primitive data types don't have operations, only classes have.
Plainly and simply, C# and Java are different languages. In C# there is the notion of object
from which almost everything derives (yes, there are exceptions the most important of which is interfaces). From object
there is a derived type called ValueType
. Derivatives of ValueType
are struct
s which have value semantics. All other derivatives of object
are reference types. All of these object
s encapsulate data and behavior (i.e., they can have methods).
string name = "alex";
Console.WriteLine(name.ToUpper());
How is this possible?
I don't understand your confusion with this code snippet. name
is an instance of string
that is definitely assigned by the string literal "alex"
and we are invoking one of the overloads of the method String.ToUpper
on name
. Then the overload of Console.WriteLine
that accepts an instance of string
is invoked. You can even do this
Console.WriteLine("alex".ToUpper());
Are they really primitives?
No. string
is not a primitive.
What am I missing here?
That C# and Java are related but very different programming languages.