How to do constructor chaining in C#

前端 未结 8 1522
挽巷
挽巷 2020-11-22 16:25

I know that this is supposedly a super simple question, but I\'ve been struggling with the concept for some time now.

My question is, how do you chain constructors

8条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 16:56

    I just want to bring up a valid point to anyone searching for this. If you are going to work with .NET versions before 4.0 (VS2010), please be advised that you have to create constructor chains as shown above.

    However, if you're staying in 4.0, I have good news. You can now have a single constructor with optional arguments! I'll simplify the Foo class example:

    class Foo {
      private int id;
      private string name;
    
      public Foo(int id = 0, string name = "") {
        this.id = id;
        this.name = name;
      }
    }
    
    class Main() {
      // Foo Int:
      Foo myFooOne = new Foo(12);
      // Foo String:
      Foo myFooTwo = new Foo(name:"Timothy");
      // Foo Both:
      Foo myFooThree = new Foo(13, name:"Monkey");
    }
    

    When you implement the constructor, you can use the optional arguments since defaults have been set.

    I hope you enjoyed this lesson! I just can't believe that developers have been complaining about construct chaining and not being able to use default optional arguments since 2004/2005! Now it has taken SO long in the development world, that developers are afraid of using it because it won't be backwards compatible.

提交回复
热议问题