#1,105 – Re-Declaring a Class-Level Variable within a Method

You can re-declare a class-level variable within a method, that is–declare a local variable having the same name as a class-level variable.  Within the scope of the method, the local variable will hide the class-level variable.

    public class MyClass
        public int x = 10;

        public void MethodA()
            double x = 4.2;

You cannot, however, reference a class-level variable before declaring the local variable, since this is interpreted as referencing the local variable before it is defined.

        public void MethodA()
            // ERROR: Can't use local variable before it's declared

            double x = 4.2;

You also can’t reference the class-level variable in an outer scope.

        public void MethodA()

            if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday)
                // ERROR: Can't declare local variable within this scope
                double x = 4.2;

#968 – Reading a Value from a Variable

Once you’ve assigned a value to a variable, you can read the value back.  You can use the variable name anywhere that a value of the appropriate type is expected.

            // Assign value to int variable
            int n = 5;

            // Read value from variable n and use it in an expression
            int result1 = n * 2;

            string info = string.Format("n={0}, result1={1}", n.ToString(), result1.ToString());


#967 – Assigning a Value to a Variable

You store a value in a variable, or assign the value, use the = operator.  The = operator is known as the simple assignment operator.

When using the simple assignment operator, the value of the right operand is computed and the result is stored in the variable that appears as the left operand.

myInteger = 5;       // 5 stored in myInteger
myInteger = 8 + 3;   // 11 stored in myInteger

The right operand is an expression containing one or more operands and operators that is evaluated to determine a resulting value.  Operands within the expression can be constants, variables, properties or the results of function calls.

            myInteger = (12 + (8 * TripleThisNumber(2))) / myDog.Age;

The left side of an assignment statement can specify a variable, a property, or an indexer access.

            myDog.Age = 12;
            myArray[2] = 42;

#709 – A Method Can Redefine a Name Present in Parent Class

Variables declared within the scope of a method can have the same name as a member of the class in which the method is declared.

For example:

    public class Dog
        public string Name { get; set; }
        public int Age { get; set; }

        public void Bark()
            string Name = "Loud Bark";

            Console.WriteLine(string.Format("{0}: WOOF!", Name));

Assigning a value to the Name variable within the Bark method has no effect on the Name property defined in the parent class.

Although this is possible in C#, reusing names in this way is not a good idea because:

  • It can lead to confusion for someone trying to understand the code
  • The method can no longer access the identically named member from the parent class (without using the this keyword)

#510 – Declaring More than One Local Variable On the Same Line

You typically declare a local variable by specifying its type, the name of the local variable and an optional initial value.

int j;
int i = 42;

You can declare more than one variable on the same line, as long as the variables all have the same type.  Each variable can optionally include an initialization.

int j, i = 42;      // Only i is assigned
string name = "Sean", motto = "Carpe Libri";
Dog d1, d2, d3;
Dog kirby = new Dog("Kirby", 12), jack = new Dog("Jack", 14);
dynamic thing1, thing2;

You can’t, however, declare multiple implicitly-typed variables on the same line.

            var i = 12, s = "Sean";   // Error: Implicitly-typed local variables cannot have multiple declarators

#341 – Defining and Using Local Variables

You can define variables within a method.  These are known as local variables.  The variables’ values can be read and written while the body of the method is executing.

The Dog.Bark method below defines two local variables–formalName and barkPhrase.

    public class Dog
        public string Name { get; set; }
        public string BarkSound { get; set; }

        public void Bark()
            string formalName = string.Format("Sir {0}", Name);
            string barkPhrase = string.Format("{0} {0}!", BarkSound);

            Console.WriteLine("{0} says {1}", formalName, barkPhrase);

Local variables can be initialized when they are declared, or they can be set to a value later.  Since C# requires definite assignment, they must be given a value before they are read.


#36 – Variable Initialization and Definite Assignment

Variables must be assigned a value before they can be used.  You can declare a variable without initializing it, but attempting to reference the value of the variable before you’ve given it a value will result in a compiler error.

 int i;
 int j = i + 1;   // Error: Use of unassigned local variable 'i'

This requirement of definite assignment before use means that you are never able to reference an unassigned variable in C#.

It’s considered good practice to initialize a variable when you declare it.  This applies to both built-in types and custom types.

When you initialize a variable, the object that it references is said to be instantiated.

 Person p = new Person();
 int i = 0;

#35 – Declaring Variables

In C#, you declare a variable by specifying a type, followed by the name of the new variable.  You can also optionally initialize the variable at the time that you declare it.

If you initialize a variable at the time that it is declared, the initializer can be a literal value, an expression, or an array initializer.

 float length;
 int age = 46;
 string s = "Sean";
 Person p;
 Person q = new Person("Herman", 12);
 object o = s;
 int yrsLeft = 100 - age;
 int[] nums = { 10, 20, 30 };
 object[] stuff = { nums, age, q };

#30 – Types, Variables, Values, Instances

In C#, a type dictates what kind of values can be stored in a variable.  A variable is a storage location for some data.  Every variable is an instance of a specific type and will have a value that can change during the lifetime of a program.

Constants are variables whose values do not change.  They also have a specific type.

Expressions resolve to a particular value when they are evaluated.  They also have a specific type.

There are a number of built-in types in C#  (e.g. int, float) as well as constructs that allow you to create your own types (e.g. class, enum).