Skip to main content

Posts

Showing posts from July 17, 2018

Default Constructors in C# (C Sharp)

What will happen if you don't specify any constructor in your class and try to call the constructor in the client code? The answer is simple, that will work, C# will automatically call the invisible default constructor without parameters, (Unless you don't specify any private constructor in the class), the following code will work.     class ClassA     {         public void DoAction( int Count)         {             Console .WriteLine( "Count: " + Count.ToString());         }     }     class Program     {         static void Main( string [] args)         {             ClassA ClsAObj1 = new ClassA ();         }     } The following code will not work:      class ClassA     {         private ClassA()         {         }         public void DoAction( int Count)         {             Console .WriteLine( "Count: " + Count.ToString());         }     }     class Program     {      

Static Constructors in C # (C Sharp)

If you want your class to be initialize the Static members and if you want anything to be executed only once then you can use the static constructor, For example:  Creating a Log file, Inform the user that the class has been called, Here is the MSDN Explanation, we will look it case by case 1) Why Static constructor actions will be performed only once regardless of times the object is created? CLR is locking the thread and making sure that only one thread is running per App Domain for specific set of purposes like writing log entries, holding session values, implementing Singletons… See the example program    class   ClassA   {     static  ClassA()         {              Console .WriteLine( "Static Constructor ClassA is called!" );         }          public  ClassA( int  Count)         {              Console .WriteLine( "Public Constructor ClassA is called! Count is :"  + Count.ToString());         }