Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Public Constructor

This C# article covers the concept of public constructors. It provides sample code.

Public constructors are most useful and common.

They allow a class to be instantiated from an external location in your program. Most constructors will be in the public accessibility domain. We use private constructors for singletons.

Private Constructor

Note: Public constructors are used to create class instances from outside the class.

Example. This program introduces two classes: the Test class, and also the Program class. The Program class is used to contain the Main method, which is where the program begins execution.

The Test class shows how to use a custom constructor that receives a parameter. Also, the Test class constructor requires that it receives a non-zero int, demonstrating parameter validation.


C# program that uses public constructor

using System;

class Test
    public Test(int a)
	if (a == 0)
	    throw new ArgumentException("Error", "a");

class Program
    static void Main()
	Test test = new Test(5);

    (The class is instantiated.)

Summary. Public constructors are the most commonly used ones. Classes without a specified public constructor will have an implicit public constructor. Private constructors, meanwhile, are most useful for protecting a class from improper use.

Tip: This has been referred to as information hiding or binary barricading. These fancy terms refer to similar concepts.