Yet Yet Another Way To Create An Object

Yep, there's still another one: FormatterServices RuntimeHelpers (.NET Core and .NET unified). This one allows one to create an object without running it's constructor... it is used by some of our good friends serializers.

Stopwatch watch = new Stopwatch();

for (Int32 i = 0; i < 100; ++i)
{
	StringBuilder builder = RuntimeHelpers.GetUninitializedObject(typeof(StringBuilder)) as StringBuilder;
}

Int64 time4 = watch.ElapsedTicks;

Beware, though: because the constructor isn't run (and remember that all fields that are initialized inline are also in fact initialized in the constructor), the object's state may be invalid.

Enough object construction for now...

Bookmark and Share

                             

3 Comments

  • What is the practical application of an uninitialized object unless you want to override the default initialization?

  • nitroxn:
    I never used it myself, but some serializers do.

  • nitroxn and arun:
    As you may know, some serializers allow serializing even objects without a public parameterless constructor; in these situations, the only chance is using FormatterServices. I am not saying that you should use it, I agree with you on its dangers, I am just saying that it can be done, and that it actually is.

Add a Comment

As it will appear on the website

Not displayed

Your website