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?

Kahn Kah
  • 1,389
  • 7
  • 24
  • 49

1 Answers1

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"

Rob
  • 45,296
  • 24
  • 122
  • 150
  • Thanks! But would I leave the first constructor completely empty then? And wouldnt my main function need an edit? – Kahn Kah Jul 26 '17 at 14:55
  • As this has been marked as a duplicate, you can probably find the answer on that question =) – Rob Jul 26 '17 at 14:58
  • 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... – Kahn Kah Jul 26 '17 at 14:59
  • 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 – Rob Jul 26 '17 at 16:36
  • Thank you very much for the explanation Rob! – Kahn Kah Jul 26 '17 at 18:03