Take the following class as an example:
class Sometype { int someValue; public Sometype(int someValue) { this.someValue = someValue; } }
I then want to create an instance of this type using reflection:
Type t = typeof(Sometype); object o = Activator.CreateInstance(t);
Normally this will work, however because SomeType
has not defined a parameterless constructor, the call to Activator.CreateInstance
will throw an exception of type MissingMethodException
with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.
What is the significance of the default constructor? They are used to create objects, which do not have any having specific initial value. Is a default constructor automatically provided? If no constructors are explicitly declared in the class, a default constructor is provided automatically.
If constructors are explicitly defined for a class, but they are all non-default, the compiler will not implicitly define a default constructor, leading to a situation where the class does not have a default constructor. This is the reason for a typical error, demonstrated by the following example.
A default constructor exists by, well... default. But, if you create your own parameterized constructor, then the compiler assumes that you want to use that one, and does not emit a default constructor anymore.
The C# language specification is quite clear in terms of what is required to instantiate an object. It states that you must use the instance constructor. An instance constructor is a member that implements the actions required to initialize an instance of a class.
I originally posted this answer here, but here is a reprint since this isn't the exact same question but has the same answer:
FormatterServices.GetUninitializedObject()
will create an instance without calling a constructor. I found this class by using Reflector and digging through some of the core .Net serialization classes.
I tested it using the sample code below and it looks like it works great:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Runtime.Serialization; namespace NoConstructorThingy { class Program { static void Main(string[] args) { MyClass myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass)); //does not call ctor myClass.One = 1; Console.WriteLine(myClass.One); //write "1" Console.ReadKey(); } } public class MyClass { public MyClass() { Console.WriteLine("MyClass ctor called."); } public int One { get; set; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With