Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing non-static fields from static functions and vice versa impossible?

I want to programmatically determine the space I've got for some controls I want to create dynamically. So, I want to get the container's height and divide it by the number of rows (a constant).

I've got this function (this code is part of the form on which the panel named dynamicPanel lives):

private static int getControlHeightToUse() {
  return (dynamicPanel.Height / NUMBER_OF_ROWS);
}

...which gives me the compile-time error, "*An object reference is required for the non-static field, method, or property RememberNextGen_CRLogins.CRLoginsMainForm.dynamicPanel'*"

I don't understand what it's trying to tell me/what it wants.

If I remove the "static":

private int getControlHeightToUse() {
  return (dynamicPanel.Height / NUMBER_OF_ROWS);
}

...I then get the compile-time error, "*A field initializer cannot reference the non-static field, method, or property 'TitanNextGen_CRLogins.CRLoginsMainForm.getControlHeightToUse()'*"

...on the indicated line below:

public partial class CRLoginsMainForm : Form {

  int controlHeight = getControlHeightToUse(); // <-- err
like image 726
B. Clay Shannon-B. Crow Raven Avatar asked Nov 26 '25 06:11

B. Clay Shannon-B. Crow Raven


1 Answers

A static method has only direct access to static memebers of the class, if you want to use instance members of the class, you must pass in an instance of the class to the method (or have one available as a static as in the case of a singleton).

Thus, you can modify your method to take in the instance member that is preventing it from being able to be static:

private static int getControlHeightToUse(Panel thePanel) 
{
  return (thePanel.Height / NUMBER_OF_ROWS);
}

Then just pass in dynamicPanel on the call...

Instance methods, however, can access static members. Remember that static members are shared among all instances and exist even if no instance of the class exist. Thus they can't call instance members since they don't know which instance you are talking about.

like image 110
James Michael Hare Avatar answered Nov 27 '25 19:11

James Michael Hare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!