0

I have the following class

public class ReportDataSource : IReportDataSource
{
    public string Name { get; set; }
    public string Alias { get; set; }
    public string Schema { get; set; }
    public string Server { get; set; }

    public ReportDataSource()
    {
    }

    public ReportDataSource(ReportObject obj)
    {
        this.Name = obj.Name;
        this.Alias = obj.Alias;
        this.Schema = obj.Schema;
        this.Server = obj.Server;
    }

    public ReportDataSource(ReportObject obj, string alias)
    {
        this.Name = obj.Name;
        this.Schema = obj.Schema;
        this.Server = obj.Server;

        this.Alias = alias;
    }

}

In constructor ReportDataSource(ReportObject obj, string alias) behaves exactly as the ReportDataSource(ReportObject obj). The only different is that I can override the alias property.

Is there a way I can call ReportDataSource(ReportObject obj) from inside ReportDataSource(ReportObject obj, string alias) so I won't have to duplicate my code?

I tried this

    public ReportDataSource(ReportObject obj, string alias)
        :base(obj)
    {
        this.Alias = alias;
    }

but I get this error

'object' does not contain a constructor that takes 1 arguments

How can I call a different constructor from with in a constructor in c#?

Jaylen
  • 39,043
  • 40
  • 128
  • 221

1 Answers1

2

Try this:

public ReportDataSource(ReportObject obj, string alias)
    :this(obj)
{
    this.Alias = alias;
}

It is sometimes called constructor chaining.

An instance constructor initializer of the form this(argument-listopt) causes an instance constructor from the class itself to be invoked. The constructor is selected using argument-list and the overload resolution rules of §7.5.3.

AlexD
  • 32,156
  • 3
  • 71
  • 65