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 methods. I’m a Java developer and my understanding was that primitive data types don’t have methods, 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?
stringis 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 beingobject). The primitive types in C# areBoolean(bool),Byte(byte),SByte(sbyte),Int16(short),UInt16,Int32(int), UInt32 (uint),Int64(long), UInt64 (ulong),IntPtr,UIntPtr,Char(char),Double(double), andSingle(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).IsPrimitiveisfalseifMyStructis a user-definedstruct.The book said this? Which book?
Plainly and simply, C# and Java are different languages. In C# there is the notion of
objectfrom which almost everything derives (yes, there are exceptions the most important of which is interfaces). Fromobjectthere is a derived type calledValueType. Derivatives ofValueTypearestructs which have value semantics. All other derivatives ofobjectare reference types. All of theseobjects encapsulate data and behavior (i.e., they can have methods).I don’t understand your confusion with this code snippet.
nameis an instance ofstringthat is definitely assigned by the string literal"alex"and we are invoking one of the overloads of the methodString.ToUpperonname. Then the overload ofConsole.WriteLinethat accepts an instance ofstringis invoked. You can even do thisNo.
stringis not a primitive.That C# and Java are related but very different programming languages.