Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Malware / Trojaner / VirenIntroducing CAIRN: Frontier tracking for AI-integrated malware(22.09.2026 um 12:00 Uhr)
IT Security NachrichtenAnother worry for water systems: infostealer exposure(22.09.2026 um 12:00 Uhr)
IT Security NachrichtenContext Bombs Trick Autonomous Qwen AI Agents Into Stopping Cyberattacks(22.09.2026 um 12:21 Uhr)
IT Security NachrichtenSideCopy: ReverseRAT per mshta.exe und Reverse-Phishing an indische Unis(22.09.2026 um 11:55 Uhr)
IT Security NachrichtenLimeLeads – 17,838,396 breached accounts(22.09.2026 um 12:02 Uhr)
Malware / Trojaner / VirenThe Closed Quorum: Inside the first reported autonomous AI C2 implant(22.09.2026 um 12:02 Uhr)
IT Security NachrichtenNorth Korean Hackers Hide Mac Backdoors in Fake Terraform Job Tests(22.09.2026 um 12:31 Uhr)
Malware / Trojaner / VirenIntroducing CAIRN: Frontier tracking for AI-integrated malware(22.09.2026 um 12:00 Uhr)
IT Security NachrichtenAnother worry for water systems: infostealer exposure(22.09.2026 um 12:00 Uhr)
IT Security NachrichtenContext Bombs Trick Autonomous Qwen AI Agents Into Stopping Cyberattacks(22.09.2026 um 12:21 Uhr)
IT Security NachrichtenSideCopy: ReverseRAT per mshta.exe und Reverse-Phishing an indische Unis(22.09.2026 um 11:55 Uhr)
IT Security NachrichtenLimeLeads – 17,838,396 breached accounts(22.09.2026 um 12:02 Uhr)
Malware / Trojaner / VirenThe Closed Quorum: Inside the first reported autonomous AI C2 implant(22.09.2026 um 12:02 Uhr)
IT Security NachrichtenNorth Korean Hackers Hide Mac Backdoors in Fake Terraform Job Tests(22.09.2026 um 12:31 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

7 Types of Constructors in C#

Constructors are special methods that execute automatically when an instance of a class is created. In C#, there are different types of constructors that allow us to initialise objects in various ways. In this article, we'll explore the 7…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!



Constructors are special methods that execute automatically when an instance of a class is created. In C#, there are different types of constructors that allow us to initialise objects in various ways. In this article, we'll explore the 7 main types of constructors with practical examples.






1. Default Constructor



The default constructor has no parameters and is provided automatically by the compiler if we don't define any constructor. However, we can define it explicitly.




public class Person
{
public string Name { get; set; }
public int Age { get; set; }

// Default constructor
public Person()
{
Name = "No name";
Age = 0;
}
}

// Usage
Person person = new Person();
Console.WriteLine($"{person.Name}, {person.Age} years old");









2. Parameterised Constructor



This type of constructor accepts parameters to initialise the object with specific values at the time of its creation.




public class Person
{
public string Name { get; set; }
public int Age { get; set; }

// Parameterised constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
}

// Usage
Person person = new Person("Adri", 30);
Console.WriteLine($"{person.Name}, {person.Age} years old");









3. Copy Constructor



A copy constructor creates a new object by copying the values from an existing object of the same type.




public class Person
{
public string Name { get; set; }
public int Age { get; set; }

public Person(string name, int age)
{
Name = name;
Age = age;
}

// Copy constructor
public Person(Person otherPerson)
{
Name = otherPerson.Name;
Age = otherPerson.Age;
}
}

// Usage
Person person1 = new Person("Anna", 25);
Person person2 = new Person(person1);
Console.WriteLine($"{person2.Name}, {person2.Age} years old");
// Output: Anna, 25 years old









4. Static Constructor



A static constructor is used to initialise static members of a class. It executes only once, before the first instance is created or any static member is accessed.




public class Configuration
{
public static string BasePath { get; set; }
public static int Timeout { get; set; }

// Static constructor
static Configuration()
{
BasePath = "C:/App/";
Timeout = 5000;
Console.WriteLine("Static constructor executed");
}
}

// Usage
Console.WriteLine(Configuration.BasePath);
// Output:
// Static constructor executed
// C:/App/









5. Private Constructor



A private constructor prevents the creation of instances of a class from outside it. It's useful for implementing patterns like Singleton or for classes with only static methods.




public class Logger
{
private static Logger instance;

// Private constructor
private Logger()
{
Console.WriteLine("Logger initialised");
}

public static Logger GetInstance()
{
if (instance == null)
{
instance = new Logger();
}
return instance;
}

public void Write(string message)
{
Console.WriteLine($"[LOG]: {message}");
}
}

// Usage
Logger logger = Logger.GetInstance();
logger.Write("Application started");
// Output:
// Logger initialised
// [LOG]: Application started









6. Constructor Chaining



Constructor chaining allows one constructor to call another constructor in the same class using the this keyword, avoiding code duplication.




public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }


public Product(string name, decimal price, string category)
{
Name = name;
Price = price;
Category = category;
}


public Product(string name, decimal price)
: this(name, price, "General")
{
}

// Another chained constructor
public Product(string name)
: this(name, 0.0m, "General")
{
}
}

// Usage
Product p1 = new Product("Laptop", 999.99m, "Electronics");
Product p2 = new Product("Mouse", 19.99m);
Product p3 = new Product("Keyboard");









7. Constructor with Optional Parameters



C# allows defining constructors with optional parameters, providing default values for some or all parameters.




public class Email
{
public string Recipient { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public bool IsUrgent { get; set; }

// Constructor with optional parameters
public Email(string recipient,
string subject = "No subject",
string body = "",
bool isUrgent = false)
{
Recipient = recipient;
Subject = subject;
Body = body;
IsUrgent = isUrgent;
}
}

// Usage
Email email1 = new Email("[email protected]");
Email email2 = new Email("[email protected]", "Meeting");
Email email3 = new Email("[email protected]", "Urgent", "Need help", true);









Conclusion



Constructors are fundamental in object-oriented programming in C#. Each type of constructor has its specific purpose:





  • Default constructor: For basic initialisations without parameters


  • Parameterised constructor: When we need specific values when creating objects


  • Copy constructor: To duplicate existing objects


  • Static constructor: To initialise static members of the class


  • Private constructor: To control instance creation (Singleton patterns)


  • Constructor chaining: To reuse code between constructors


  • Constructor with optional parameters: For greater flexibility in object creation



Mastering these concepts will allow you to write cleaner, more maintainable, and efficient code in C#.

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten 7 Types of Constructors in C#

Thematisch verwandte Begriffe: Types, Constructors · 6 Treffer

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-94493 | A vulnerability was detected in Gigatech PDV5701 1.0.31_240305_112640. T…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick