Variable Declaration and Extension in C #

advertisements

I'm new to C# and have some trouble with the variable scope.

 if(number > 10)
 {
      int someNr = 5;
 }
 else
 {
      /* .... */
 }

 if(number2 < 50)
 {
      someNr = 10; /* PRODUCES AN ERROR */
 }
 else
 {
     /* ........ */
 }

I know that if number is not > 10 then someNr will not be declared as int. But should I wrote two times int someNr? What if both if are true? Double declaration? Is this a problem should I declare the variable outside the if?

Class variables

PHP

class TEST {
   private $test = 'test';

   private function testVariable(){
       /* Not declared */
       echo $test;
   }

   private function testVariable2(){
       /* echo 'test' */
       echo $this->test;
   }
}

C#

class TEST {
   private string test = "test";

   private void testVariable(){
       /* takes the value of class variable test */
       test;
   }

   private function testVariable2(){
       /* takes also the value of class variable 'test' */
       this.test;
   }
}

But what if

C#

class TEST {
   private string test = "test";

   private void testVariable(){
       string test = "somethingOther";

       Console.WriteLine(test);
   }
}

test is "test" or "somethingOther"?

Which has the priority? The class variable or the local-method variable?


To set the variable inside an if statement you should declare it outside the if statement, otherwise it will be a local variable only available inside the if statement:

int someNr;
if(number > 10)
{
  someNr = 5;
}
else
{
  /* .... */
}

if(number2 < 50)
{
  someNr = 10;
}
else
{
  /* ........ */
}

Note: You also need to set some value to the variable in the else blocks, or set an initial value when you define it, otherwise it's not known to always have a value.


In your class TEST the local variable will shadow the class member:

class TEST {
  private string test = "test"; // this is a member of the class

  private void testVariable(){
    string test = "somethingOther"; // this is a local variable that shadows the class member

    Console.WriteLine(test); // this will use the local variable, it can't see the class member
  }
}