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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

Just Browsing Browsing

[4] html - How to create even cell spacing within a

548k questions

547k answers

4 comments

86.3k users

...