0

This is my C# coding. I want to increment the variable counter every times I recall this function. Is there any way to make the counter variable increment by 1 every times I recall this function?

private void _CalculateValue()
{
     double b = 0.1;

     int counter = 0;

     a = a * b;

     counter++;    
}
2
  • Counter is being incremented in your code. Although, this seems to serve no purpose since the same counter variable will never be touched again after the function has finished executing.
    – Rohan
    Oct 4, 2013 at 1:08
  • 1
    can you add a static field to the class containing this method to increment?
    – Harrison
    Oct 4, 2013 at 1:10

3 Answers 3

4

How about

class customClass
{

    int classLevelCounter = 0;

    private void _CalculateValue()
    {
        double b = 0.1;

        a = _a * b;

        classLevelCounter++;
    }

}

In your question counter is created in the method and destroyed (looses its value) as soon as method gets over since its scope is only method. Hence next time it will again initialize from 0.

In my answer the classLevelCounter retains its value even after method gets over as its scope is Class.

Here is a working example.

enter image description here

3
  • The variable would not be global. It's class-level. Oct 4, 2013 at 1:10
  • I think all of these examples need to have the variable as static and/or be in a static class. I guess we need to know if this is counter will be different for each object, but this type of method doesn't appear to be.
    – Harrison
    Oct 4, 2013 at 1:19
  • @Harrison: No that is not necessary. Look at the picture. Oct 4, 2013 at 1:54
0

You need to do this:

int counter = 0;

private void _CalculateValue()
{
    double b = 0.1;

    a = _a * b;

    counter++;    
}
0

Just need to move the variable declaration outside of the method.

class myClass
{    
    int counter = 0;
    private void _CalculateValue()
    {
         double b = 0.1;
         a = a * b;
         counter++;    
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.