Use of Private Constructors in C# (.NET)
Here is an example of a Private Constructor
public class WicketCounter { //Private Constructor private WicketCounter() { } // No of Wickets public static int Wickets; // Public Method to Return the No of Wickets public static int WicketCount() { return ++Wickets; } }
The Class has a private constructor, a public static method and a static variable. The Method increments the Wicketcount (and hence the class itself is called wicketcounter) and the value is returned through Wickets var
WicketCounter.WicketCount(); MessageBox.Show(WicketCounter.Wickets.ToString());
The declaration of private constructor prevents the creation of default constructor. Hence the class cannot be instantiated and doesn;t contain any instance fields or methods
No comments:
Post a Comment