📜  c# struct constructor (1)

📅  最后修改于: 2023-12-03 14:59:40.913000             🧑  作者: Mango

C# Struct Constructor

In C#, a struct can have a constructor, which is a special method that is used to initialize the values of its fields when the struct is created. In this article, we'll explore how to define and use constructors in C# structs.

Defining Constructors in C# Structs

To define a constructor for a struct, we use the same syntax as for a class constructor, but with the keyword struct instead of class.

Here's an example of a struct with a parameterized constructor:

public struct Person
{
    public string Name;
    public int Age;

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

In this example, the Person struct has two fields: Name and Age. The constructor takes two parameters, name and age, and initializes the fields with these values.

Using Constructors in C# Structs

When we create a struct object, the constructor is automatically called to initialize its fields. We can create a struct object using the new keyword and passing the arguments to the constructor:

Person person = new Person("John Doe", 30);

In this example, we create a Person object with the name "John Doe" and age 30.

Default Constructors in C# Structs

If we don't define any constructor for a struct, C# provides a default constructor that initializes all the fields to their default values. For value types such as structs, the default value is 0 for numeric types and null for reference types.

We can also define a parameterless constructor for a struct, which is useful when we want to create an object with default values. Here's an example:

public struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }

    public Point() : this(0, 0) { }
}

In this example, the Point struct has two fields X and Y and two constructors: a parameterized constructor that takes x and y parameters, and a parameterless constructor that calls the parameterized constructor with default values of 0 for both X and Y.

Conclusion

Constructors in C# structs are used to initialize the values of their fields when the struct is created. We can define parameterized constructors, default constructors, and even overload constructors with different parameters. By using constructors effectively, we can create robust and maintainable code.