How to use multi constructor and call another constructor from base constructor in C#

2 Answers

0 votes
using System;

class Worker
{
    public Worker() : this(0, "aaa") {
        // this constructor activate -> Worker(int age, string name) with -> this(0, "aaa")
        Console.WriteLine("Worker()");
    }

    public Worker(int age, string name) {
        Console.WriteLine("Worker(int age, string name) = {0}, {1}", age, name);
    }
}

class Program {
    static void Main() {
        Worker w = new Worker();
    }
}



/*
run:

Worker(int age, string name) = 0, aaa
Worker()

*/

 



answered Sep 8, 2020 by avibootz
0 votes
using System;

class Worker
{
    public Worker() : this(0, "aaa") {
        // this constructor activate -> Worker(int age, string name) with -> this(0, "aaa")
        Console.WriteLine("Worker()");
    }

    public Worker(int age, string name) {
        Console.WriteLine("Worker(int age, string name) = {0}, {1}", age, name);
    }
}

class Program {
    static void Main() {
        Worker w = new Worker(32, "Tom");
    }
}



/*
run:

Worker(int age, string name) = 32, Tom

*/

 



answered Sep 8, 2020 by avibootz

Related questions

1 answer 169 views
1 answer 208 views
1 answer 172 views
1 answer 135 views
135 views asked Sep 8, 2020 by avibootz
1 answer 171 views
1 answer 155 views
...