0

I'm trying to make a number that increases by a different amount every time (increment), but the value of that number is not random. It follows an equation which has only 1 dynamic integer, being the "everincreasing" one. But I've run into a snag as I'm trying to make my WFA do this in a public int. And it's giving me an error on my everincreasing in the formula.

This number is to be used as an incremental number to add on everytime it runs. And everytime it runs, it adds 1 to the everincreasing.

public partial class Form1 : Form
{
    public int everincreasing = 1;
    public int increment = Convert.ToInt32(Math.Floor(everincreasing + 300 * Math.Pow(2, everincreasing / 7)));
}

When I hover over everincreasing the error tooltip says: A field initializer cannot reference the non-static field, method, or property 'Form1.everincreasing'

I looked for this exception on the msdocs for c# and I was unable to find how to fix it, so I'm here asking the question I couldn't figure out how to fix in msdocs.

John Olivas
  • 309
  • 1
  • 2
  • 14
  • https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property – Mitch Wheat Jan 04 '19 at 05:49
  • 2
    Possible duplicate of [A field initializer cannot reference the nonstatic field, method, or property](https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property) – user247702 Jan 04 '19 at 07:06

1 Answers1

1

good explanation on that error from this SO answer -

This happens because - You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before defaultReminder, so the above line might throw a NullReferenceException.

In other words you can't use your everincreasing variable here:

public int increment = Convert.ToInt32(Math.Floor(everincreasing + 300 * Math.Pow(2, everincreasing / 7)));

because there is no guarantee that it will be initialized before your increment variable.

I would rather try use a method to achieve this if possible e.g.

public int Increment()
{
   return Convert.ToInt32(Math.Floor(everincreasing + 300 * Math.Pow(2, everincreasing / 7)));
}

or increment your value in the form constructor:

public Form1()
{
   increment = Convert.ToInt32(Math.Floor(everincreasing + 300 * Math.Pow(2, everincreasing / 7)));
}
majita
  • 1,278
  • 14
  • 24