Friday, June 18, 2010
No(n parameter) constructor in Value Type
There are two key types in .NET framework (1) Value (2) Reference. As we know, value consumes stack and reference uses heap memory to store direct and indirect data. On working in Value type .NET objects, got the quite
interesting observation.
In terms of constructor, there are two significant differences between value and reference types.
1. Value type can't define non-parameter constructor where as reference will.
2. If no constructor is defined, .NET Compiler can produce default non-parameter constructor for reference type, where as value type can't.
1. Non parameter
On writing the below code with parameterless constructor, .NET compiler throws the error 'Structs cannot contain explicit parameterless constructors'
public struct RectangleInfo {
public RectangleInfo() {
2. No constructor
On using ILDASM to inspect the members of the value type, a parameterless constructor is not a member of the structure as marked in the attached image. But during the app execution, .NET framework has ability to instantiate a value type by using a language's constructor called implicit default constructor.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment