DEV Community

Matthew Cullen
Matthew Cullen

Posted on

1 1

C# Constructor Overloading Example

using System;

namespace LESSON2_ConstructorHandsOn
{
    class Program
    {
        static void Main(string[] args)
        {
            Owner momo = new Owner("Momo");
            Cat ownedCat = new Cat("Lennny", momo);
            Cat unownedCat = new Cat("Buddy");
        }
    }

    class Cat
    {
        public string Name { get; set; }
        public Owner Owner { get; set; }

        public Cat(string name)
        {
            Name = name;
            Console.WriteLine($"ADDED CAT: {Name}");
        }

        public Cat(string name, Owner owner)
        {
            Name = name;
            Owner = owner;
            Console.WriteLine($"ADDED CAT: {Name}, OWNER: {Owner.Name}");
        }
    }

    class Owner
    {
        public string Name { get; set; }

        public Owner(string name)
        {
            Name = name;
            Console.WriteLine($"ADDED OWNER: {Name}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
//// OUTPUT
//ADDED OWNER: Momo
//ADDED CAT: Lenny, OWNER: Momo
//ADDED CAT: Buddy
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay