Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why colon on constructor chaining doesn't work?

I have a problem while I was study by myself today I did follow everything in the lecture structure carefully but I end up having CS1073 problem…

using System;
using System.Collections.Generic;
using System.Text;

namespace Shape_Rectangle
{
    class AExample
    {
        public void animal()
        {
            Console.WriteLine("C A");
        }
        public void animal(string p1)
        {
            Console.WriteLine("C B" + p1);
        }
        public void animal(string p1, string p2) : this(p1)
        {
            Console.WriteLine("C C" + p2);
        }
    }
}

and it keep saying that the ":" in this -> public void animal(string p1, string p2) : this(p1)
is having a problem anyone have any idea what did I do wrong here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are right in thinking that the colon is used to chain constructors. However your constructors are not well formed and are therefore acting like methods instead.

Here is an excerpt from the microsoft documentation:

A constructor is a method whose name is the same as the name of its
type. Its method signature includes only an optional access modifier,
the method name and its parameter list; it does not include a return
type.

As your class is called "AExample", your constructors should also be called "AExample" and not "animal". Your constructors should also not include the return type, which in this case is "void".

To fix your code, try this:

class AExample
{
    public AExample()
    {
        Console.WriteLine("C A");
    }
    public AExample(string p1)
    {
        Console.WriteLine("C B" + p1);
    }
    public AExample(string p1, string p2) : this(p1)
    {
        Console.WriteLine("C C" + p2);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading