DEV Community

Discussion on: C# value type variables and reference type variables (Question)

Collapse
 
jayjeckel profile image
Jay Jeckel

Yes, the string literal "Richard" has the type String and 24 literal has the type Int32.

The new keyword is how we tell the compiler to instance arbitrary types when we need them. Literals are similar, when you type "Richard" you are telling the compiler to instance a String type object with the given content and 24 is telling the compiler to instance a Int32 object with the value of twenty-four.

You can instance string objects yourself. For example, one string constructor takes a length and a char to fill that length, eg new string('=', 10) instances a string object with content the same as the literal "==========".

I don't think the number types have useful constructors, but you can manually instance them if you want, ie int num = new Int32(). That will give you a variable that is equal to the default value of the type, which in this case would be zero.

Lastly, you can find out the type of any object, literal or otherwise, using the GetType() method, such as Console.WriteLine("Richard".GetType()); which would write System.String to the console.