Creating instance of type without default constructor in C# using reflection
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;
}
}
}
Activator.CreateInstance(Type) for a type without parameterless constructor
See this: Creating instance of type without default constructor in C# using reflection
Here's to the future also, this is in regards to C# 4.0:
Posted by Microsoft on 1/4/2010 at
2:08 PM
We have reviewed your bug and
have determined that the behavior that
you described is by design. We are now
archiving this issue. Thanks for using
Visual Studio and the .Net Framework!There are many overloads of Activator.CreateInstance, the one that
takes a single type parameter only
invokes the default parameterless
constructor. Constructors that take an
optional parameter like the one in
your example are not default
constructors. To invoke them you need
to:
- use an overload that takes an argument array
- Pass in Type.Missing as the argument
- Specify OptionalParamBinding in the BindingFlags
Here is an example:
Activator.CreateInstance(typeof(MyClassName),
BindingFlags.CreateInstance |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.OptionalParamBinding,
null, new Object[] {Type.Missing}, null);
Thanks,
Weitao Su
Microsoft Corp.
Create object of type determined at runtime with non-default constructor
If you are expecting there to be a parameter that takes a TableData
, then this is simply:
Type type = Type.GetType(qualifiedName);
TableData tableData = ...
A obj = (A)Activator.CreateInstance(type, tableData);
Noting that the qualifiedName
should include the assembly information; if it doesn't, you'll want to resolve that first - perhaps:
Type type = typeof(A).Assembly.GetType(fullName);
where B
/ C
etc is in the same assembly as A
, and where fullName
is "Namespace.B"
or similar.
Non-default constructor for runtime determined type
Three options:
- Use
Type.GetConstructor
and thenConstructorInfo.Invoke
- Use one of the overloads of
Activator.CreateInstance
which takes arguments. - If you already know all the possible types beforehand, create a
Dictionary<Type, Func<string, string, YourBaseType>>
or whatever's appropriate
The third option requires you to change your factory code each time you add a new type, of course - but it's only a single line.
Personally I like the first option, as it gives you the most control (rather than relying on Activator.CreateInstance
finding the best matching constructor at execution time) - and if this is performance-sensitive code, you could build a dictionary of delegates at execution time by discovering the constructors, then using expression trees. (As far as I can tell, you can't build a delegate from a constructor using Delegate.CreateDelegate
, which is somewhat annoying.)
Create object instance without invoking constructor?
I have not tried this, but there is a method called FormatterServices.GetUninitializedObject that is used during deserialization.
Remarks from MSDN says:
Because the new instance of the object
is initialized to zero and no
constructors are run, the object might
not represent a state that is regarded
as valid by that object.
Related Topics
List<T> Orderby Alphabetical Order
Does .Net Provide an Easy Way Convert Bytes to Kb, Mb, Gb, etc.
Differencebetween Directory.Enumeratefiles VS Directory.Getfiles
C# Little Endian or Big Endian
Enter "&" Symbol into a Text Label in Windows Forms
Transparency for Windows Forms Textbox
Visual Studio "Could Not Copy" .... During Build
How to Use the Ternary Operator Inside an Interpolated String
Read Connection String from Web.Config
C# Selenium 'Expectedconditions Is Obsolete'
How to Pass SQLparameter to In()
Silent Failures in C#, Seemingly Unhandled Exceptions That Does Not Crash the Program
What Does Placing a @ in Front of a C# Variable Name Do
Parameterized Queries VS. SQL Injection
String = String + Int: What's Behind the Scenes
There Is No Argument Given That Corresponds to the Required Formal Parameter - .Net Error