Yet Yet Another Way To Create An Object

Posted by Ricardo Peres on ASP.net Weblogs See other posts from ASP.net Weblogs or by Ricardo Peres
Published on Tue, 06 Apr 2010 13:44:43 GMT Indexed on 2010/04/06 13:53 UTC
Read the original article Hit count: 303

Filed under:
|

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

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about reflection