What is int in c#?
-
22-06-2021 - |
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;
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