Question

What is int in C#? Is it a keyword, or is it a class derived from system.ValueTypes? If it is a keyword then how do the following lines compile

int i = new int(); // If int is not a class then how does it have a default constructor

Console.WriteLine(i.ToString()); // If int is not a class then how does it have member functions

If int is a class then why is it not necessary to always initialize it with new? How does the following line compile?

int i = 8;
Was it helpful?

Solution

The int is an alias of CTS type System.Int32 structure.

Read SO answer posted by Eric Lippert - How do ValueTypes derive from Object (ReferenceType) and still be ValueTypes?

OTHER TIPS

int is a keyword that is an alias for the value type (struct) System.Int32.

Being a regular value type, I believe its inheritance is System.Object -> System.ValueType -> System.Int32.

Because int has a literal notation, like strings and other number types, you can create instances of it without new.

To explain code with code:

Console.WriteLine(typeof(int) == typeof(Int32)); // Outputs: True
Console.WriteLine(typeof(int).Name); // Outputs: Int32
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top