This post originated from an RSS feed registered with .NET Buzz
by Scott Hanselman.
Original Post: More interesting code from my buddy Sairama - How to create an object with a private constructor
Feed Title: Scott Hanselman's ComputerZen.com
Feed URL: http://radio-weblogs.com/0106747/rss.xml
Feed Description: Scott Hanselman's ComputerZen.com is a .NET/WebServices/XML Weblog. I offer details of obscurities (internals of ASP.NET, WebServices, XML, etc) and best practices from real world scenarios.
using System; namespace Corillian.Testing { class PrivateClass { publicstring Name; publicint Age; private PrivateClass() { Name = "not initialized"; Age = 0; } }
class Test { staticvoidMain(string[] args) { /// The following statement will not work as the constructor is private /// PrivateClass newpTest = new PrivateClass(); /// But you can create the object through Serialization PrivateClass ptest = (PrivateClass)System.Runtime.Serialization.FormatterServices.GetUninitializedObject( typeof(PrivateClass) ); ptest.Name = "Scott"; ptest.Age = 0x1D;