0

Been trying to figure out why I am unable to initialize new objects with property values. Probably overlooking something very basic - but can't grasp what it is. Hopefully I can phrase my question in such a way that it will be useful for others as well.

In my Main class I have the following code which calls a custom usercontrol that I have defined in another class.

BallUc ball = new BallUc {
   Number = 100
};
MessageBox.Show(ball.Number.ToString()); //this works and returns '100'.

Relevant part of my BallUc code;

private int _number { get; set; }
public int Number{
  get { return _number ; }
  set { _number = value; }
}

public BallUc() {
  InitializeComponent();
  MessageBox.Show(this.Number.ToString()); //this doesn't work and returns '0'.
}

I need the number variable to compute some functions in the BallUc class. Hope that my question is clear, if anything needs clarification please let me know. Thank you in advance for your time!

WalterB
  • 110
  • 2
  • 12

3 Answers3

3

Property assignment by object initializers is done after the constructor has executed. If you need the value to be available in the constructor, you have to pass it as argument:

public BallUc(int number)
{
    InitializeComponent();
    Number = number;
    MessageBox.Show(Number.ToString());
}

Then instantiate your control like this:

var ball = new BallUc(100);
Community
  • 1
  • 1
Clemens
  • 123,504
  • 12
  • 155
  • 268
1

The constructor is executed before you set the value on the property

mr carl
  • 571
  • 2
  • 6
  • 20
0

You can pass this parameter through constructor properties:

private int _number { get; set; }
public int Number{
  get { return _number ; }
  set { _number = value; }
}

public BallUc(int number) {
  Number = number;
  InitializeComponent();
  MessageBox.Show(this.Number.ToString());
}
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50