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#?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked! thank you. I'll accept your answer when time permits

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.