TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

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.

ArgumentException

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

Result
    (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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf