Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of colon in C# constructor header

Tags:

c#

constructor

Below is the constructor of a struct named Complex with two member variables, Real and Imaginary:

public Complex(double real, double imaginary) : this()
{
 Real = real;
 Imaginary = imaginary;
}

What is the use of the part after the colon in the function header?

like image 583
ankit0311 Avatar asked Jun 01 '12 15:06

ankit0311


People also ask

What does the colon operator do?

Colon operator (":") in R is a function that generates regular sequences. It is most commonly used in for loops, to index and to create a vector with increasing or decreasing sequence. It is a binary operator i.e. it takes two arguments.

What is the use of double colon in C?

The Scope Resolution Operator in C++ Two colons (::) are used in C++ as a scope resolution operator. This operator gives you more freedom in naming your variables by letting you distinguish between variables with the same name.

What is colon structure?

The colon has the typical histological structure as the digestive tube: mucosa, submucosa, muscularis and serosa/adventitia. The mucosa is lined by simple columnar epithelium (lamina epithelialis) with long microvilli. It is covered by a layer of mucus which aids the transport of the feces.

What does || mean in C?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.


2 Answers

You can always make a call to one constructor from within another. Say, for example:

public class mySampleClass
{
    public mySampleClass(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age) 
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}

this refers to same class, so when we say this(10), we actually mean execute the public mySampleClass(int Age) method. The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method.

In your case it going to call default constructor without any parameter

like image 95
Pranay Rana Avatar answered Oct 18 '22 21:10

Pranay Rana


It's called constructor chaining - where it's in fact calling another constructor (which takes no params in this case), and then comes back and does any additional work in this constructor (in this case setting the values of Real and Imaginary).

like image 27
Bridge Avatar answered Oct 18 '22 21:10

Bridge