Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

.net - : this(foo) syntax in C# constructors?

Every now and then, I bump into syntax that I've seen before, but never used. This is one of those times.

Can someone explain the purpose of ":this" or ":base" following a C# constructor method?

For example:

public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
{
}

My gut feeling is that it is used to map a default argument onto another constructor method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your gut feeling is right. The syntax is used to call overloaded constructors in the same class:

public class Test
{
    public Test() : this("Called from default constructor") { }
    public Test(String msg)
    {
        Console.WriteLine(msg);
    }
}

The following code:

public static void Main(String[] args)
{
    Test t1 = new Test();
    Test t2 = new Test("Called from Main function");
}

Outputs the following

Called from default constructor
Called from main function

Similarly, : base(someParams) is used to call base constructors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...