1

I have a Winforms app with the following constructors:

public Form1() { InitializeComponent(); //Code that enables/disables buttons etc } public Form1(int ID) { searchByID = ID; InitializeComponent(); //Code that enables/disables buttons etc } 

Which one gets choosen? That depends if the program is started by CMD with an added parameter. This is the main that checks that:

static void Main(string[] args) { //Args will be the ID passed by a CMD-startprocess (if it's started by cmd of course if (args.Length == 0) { Application.Run(new Form1()); } else if(args.Length>0) { string resultString = Regex.Match(args[0], @"\d+").Value; incidentID = Int32.Parse(resultString); try { Application.Run(new Form1(incidentID)); } catch (Exception e) { MessageBox.Show(e.ToString()); } } } 

My question was:

How can I optimize the constructors? They both contain about 30 lines of as good as the same code and I wanted to fix this by doing:

 public Form1() { Form1(0) } public Form1(int ID) { if (ID>0) { //it has an ID }else { doesn't have an ID } } 

but this gives me the error:

Non-invocable member cannot be used like a method.

How can I optimize this?

3
  • 2
    The keyword here being "chaining" rather than "overloading" Commented Jul 26, 2017 at 14:52
  • Try to have as little logic in the constructor as possible. No logic other than assigning variables should be acceptable. Commented Jul 26, 2017 at 14:55
  • Thanks Bender. I have no logic in my constructors. Only linking event handlers, hiding/showing buttons etc. I would assume this is correct Commented Jul 26, 2017 at 14:57

1 Answer 1

2

What you need to do is:

public Form1() : this(0) { } public Form1(int ID) { if (ID>0) { //it has an ID } else { //doesn't have an ID } } 

This is called chaining constructors together - so the : this(0) means "before you run the code in this constructor, call the other one and pass "0" in as its parameter"

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

5 Comments

Thanks! But would I leave the first constructor completely empty then? And wouldnt my main function need an edit?
As this has been marked as a duplicate, you can probably find the answer on that question =)
Thanks, the linked question doesn't explain what was wrong with my first proposal to fixing it though since the question-asker didn't have an error like mine...
Ahh, ok. Well, in your solution you're trying to call the other constructor directly yourself (where you have Form1(0)) which is not allowed, hence the error you got. By "special casing" the syntax for calling one constructor from another (to : this(0)) it ensures that the other constructor is always called first - i.e. you don't get to choose where / when your constructor calls another one
Thank you very much for the explanation Rob!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.