Zum Hauptinhalt springen
•
Sichere Programmierung📒LedgerFriend — From Everyday Transactions to Smarter Books.(03.10.2026 um 13:56 Uhr)
•
Sichere ProgrammierungMake Your Buttons Dodge the Cursor with a Wrium Plugin(03.10.2026 um 13:57 Uhr)
••
Sichere ProgrammierungWeek 2: Learning Python, Cloud, DevOps, Terraform, SSH, and CLI Basics(03.10.2026 um 13:58 Uhr)
•••
Sichere ProgrammierungEF Core 10 Is INSANE - Overview of Game Changer features(03.10.2026 um 13:59 Uhr)
••••
Sichere Programmierung📒LedgerFriend — From Everyday Transactions to Smarter Books.(03.10.2026 um 13:56 Uhr)
•
Sichere ProgrammierungMake Your Buttons Dodge the Cursor with a Wrium Plugin(03.10.2026 um 13:57 Uhr)
••
Sichere ProgrammierungWeek 2: Learning Python, Cloud, DevOps, Terraform, SSH, and CLI Basics(03.10.2026 um 13:58 Uhr)
•••
Sichere ProgrammierungEF Core 10 Is INSANE - Overview of Game Changer features(03.10.2026 um 13:59 Uhr)
•••
Intelligence View
⚡ tsecurity.de Intelligence

Constructors, Destructors and this in C#

Originally published at https://allcoderthings.com/en/article/csharp-constructor-destructor-and-this In C#, classes and structs have special methods that…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Social ReaktionenReagiere als Erste:r — dein Feedback zählt!

Originally published at https://allcoderthings.com/en/article/csharp-constructor-destructor-and-this




In C#, classes and structs have special methods that define how objects are created and destroyed. A constructor runs when an object is created and assigns initial values. A destructor is called just before an object is removed from memory. The this keyword refers to the current instance of the class and is especially useful with parameters of the same name or for method chaining.









Constructor



A constructor is a special method with the same name as the class. It is executed automatically when a new object is created and is commonly used to assign initial values. It can take parameters and can be overloaded. If no constructor is defined, C# provides a default (parameterless) constructor.





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

// Parameterless constructor
public Product()
{
Name = "Unknown";
Price = 0;
}

// Parameterized constructor
public Product(string name, decimal price)
{
Name = name;
Price = price;
}

public void Print()
{
Console.WriteLine($"{Name} - {Price:0.00} USD");
}
}

class Program
{
static void Main()
{
var p1 = new Product(); // parameterless
var p2 = new Product("Notebook", 45m); // with parameters

p1.Print(); // Unknown - 0.00 USD
p2.Print(); // Notebook - 45.00 USD
}
}












Destructor



A destructor is defined by prefixing the class name with ~ and it cannot take parameters. It is called right before an object is cleaned up from memory by the Garbage Collector. While it can be used for cleanup operations like closing files or releasing memory, the .NET Garbage Collector usually makes manual destructors unnecessary.




public class Logger
{
public Logger()
{
Console.WriteLine("Logger started.");
}

~Logger()
{
Console.WriteLine("Logger cleaned up from memory.");
}
}

class Program
{
static void Main()
{
var log = new Logger();
log = null;

// Trigger Garbage Collector
GC.Collect();
GC.WaitForPendingFinalizers();
}
}












The this Keyword



this refers to the current instance of a class. It is used to distinguish between parameters and properties with the same name, for method chaining, or to call another constructor within the same class.




public class Customer
{
public string Name { get; set; }
public string Email { get; set; }

// Constructor with parameter names same as property names
public Customer(string name, string email)
{
this.Name = name; // assignment using this
this.Email = email;
}

// Method chaining
public Customer SetName(string name)
{
this.Name = name;
return this;
}

public Customer SetEmail(string email)
{
this.Email = email;
return this;
}

public void Print()
{
Console.WriteLine($"{Name} - {Email}");
}
}

class Program
{
static void Main()
{
var c = new Customer("John", "[email protected]")
.SetName("Michael")
.SetEmail("[email protected]");

c.Print(); // Michael - [email protected]
}
}












Calling a Constructor with this



You can call one constructor from another within the same class using this(...). This approach reduces repetitive code and centralizes shared initialization logic.




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

public Person(string name) : this(name, 0) // calls another constructor
{
}

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

public void Print()
{
Console.WriteLine($"{Name} ({Age})");
}
}

class Program
{
static void Main()
{
var p1 = new Person("Alice");
var p2 = new Person("Mary", 25);

p1.Print(); // Alice (0)
p2.Print(); // Mary (25)
}
}












TL;DR





  • Constructor: Runs when an object is created and assigns initial values.

  • Destructor: Runs before an object is removed from memory; rarely needed since GC handles cleanup.

  • this: Refers to the current object; used for distinguishing parameters, method chaining, and calling constructors.


Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Constructors, Destructors and this in C#

Thematisch verwandte Begriffe: Constructors, Destructors, this · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

💬 Kommentare werden geladen…
Zum Aktualisieren ziehen
Nächster Beitrag