Scott Hanselman

More interesting code from my buddy Sairama - How to create an object with a private constructor

August 07, 2003 Comment on this post [3] Posted in Web Services
Sponsored By

using System;
namespace Corillian.Testing
{
 
     class PrivateClass
      {
            public string Name;
            public int    Age;
            private PrivateClass() 
            { 
                  Name = "not initialized";
                  Age = 0;
            }
      } 

      class Test
      {
            static void Main(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;

                  Console.WriteLine( String.Format("{0} {1}",ptest.Name,ptest.Age );
            }
      }
}

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
August 08, 2003 23:21
Why not just use a singleton to return an instance?
August 09, 2003 7:58
IIRC, this isn't a safe way to create an object, as its fields aren't initialized, nor are any constructors called.
August 09, 2003 9:59
All true my friends...I never said it was yummy, I just said it worked. ;) It's helped me to know and it's useful for VERY specific test cases...but as you both point out, teach a man to shoot, and he can shoot his foot off.

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.