Languages
[Edit]
PL

C# - konstruktor domyślny

10 points
Created by:
Marcino
720

W języku C#, programując obiektowo mamy możliwość tworzenia konstruktorów domyslnych. Konstruktor domyślny to taki, który konfiguruje obiekt w domyślnym stanie dla wskazanej klasy nie przyjmując żadnych argumentów.

Szybkie rozwiązanie:

public class ClassName
{
    private string field;

    public ClassName() // <-- konstruktor domyślny: ustawia domyślne wartości dla składowych klasy
    {
        this.field = ""; // np. domyślnie string może być pusty
    }
}

Wskazówka: to programista decyduje co rozumie pod pojęciem domyslnego stanu klasy, którą tworzy.

 

Praktyczny przykład

public class Program
{
    public static void Main()
    {
        Student student = new Student();

        // ciąg dalszy programu ...
    }
}

public class Student
{
    private string name;

    public Student() // ustawia pustą nazwę studenta jako domyślny stan klasy
    {
        this.name = "";
    }
}

 

Zobacz także

  1. C# - czym jest konstruktor w programowaniu obiektowym?

  2. C# - konstruktor kopiujący

Referencje

  1. Składnia konstruktora - Konstruktory (Przewodnik programowania w języku C#)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join