Skip to main content

Posts

Showing posts with the label C# Constructors

C#: How to call base class constructor in the derived class?

Suppose you have a class which is derived from a base class you want to do some action on when the base class object is initialized but you don’t want to alter the base class constructor or you don’t have the rights to modify the base class constructor then C# comes in handy to provide a mechanism to do the logic in your derived class itself. You need to use the base keyword to do this task,    class BaseClass1     {         public BaseClass1()         {             Console .WriteLine( "BaseClass1() Called! " );         }         public BaseClass1( int Count)         {             Console .WriteLine( "BaseClass1(int Count) Called! " );         }     }     class DerivedClass1 : BaseClass1     {         public DerivedClass1()             : base ()         {             Console .WriteLine( "DerivedClass1() Called! " );         }     }     class Program     {         static void Main( string

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());         }