为何Int32默认构造函数无参?int x=6赋值原理及new Int32(6)失效原因
int x = 6 Works But Int32 x = new Int32(6) Doesn't Great question! Let's unpack this confusion around C# value types and how the compiler handles them step by step.
First, a quick clarification: int is just an alias for System.Int32—they're exactly the same type under the hood. The difference here isn't between the two names, it's how you're initializing the variable.
Why new Int32(6) fails
If you look at the Int32 source code, you'll notice it only has a parameterless constructor. For value types (like int, bool, or custom structs), the parameterless constructor is implicit (even if you don't explicitly define it) and its sole job is to initialize the type to its default value (for int, that's 0). There's no built-in constructor that takes an integer argument, which is why trying to call new Int32(6) throws a compile error.
How int x = 6 works (and how m_value gets set)
When you write int x = 6, you're not calling a constructor at all. This is a literal assignment that the C# compiler handles specially, bypassing constructor logic entirely.
Here's the breakdown:
- Value types like
Int32are stored as direct values in memory (not as references to objects). Theinternal int m_valueyou spotted is the actual storage slot for the integer's value. - The compiler has intimate knowledge of how value types are structured, including that internal
m_valuefield. Instead of invoking a constructor, it generates low-level IL code that loads the literal6onto the stack, then directly stores that value into the memory location allocated forx—which maps directly tom_value. This is an efficient, direct operation that skips the constructor entirely.
A quick side note on new Int32()
If you did write Int32 x = new Int32(), that would initialize x to 0 (the default value for int). But even here, the compiler isn't running some complex constructor logic—it's just generating code to set m_value to 0 directly.
内容的提问来源于stack exchange,提问作者csharp newbie

