Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

Yet Yet Another Way To Create An Object

Yep, there's still another one: FormatterServices. 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 = FormatterServices.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

Comments

nitroxn said:

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

# April 6, 2010 10:40 AM

Ricardo Peres said:

nitroxn:

I never used it myself, but some serializers do.

# April 6, 2010 1:22 PM

Ricardo Peres said:

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.

# April 7, 2010 7:58 AM