Local Variable vs Field vs Method

Local variables in C# must be initialized before they are used.

https://msdn.microsoft.com/en-us/library/vstudio/s1ax56ch(v=vs.100).aspx

class Test
{

static int test1; // static field test1 = 0 Warning CS0414: The field ‘Test.test1’ is assigned but its value is never used

int test2; // instance field test2 = 0 Warning CS0649: The field ‘Test.test2’ is never assigned to, and will always have its default value 0

public void Foo() // instance method
{

int test3;                 // Declaration only; Not initialized warning CS0168: The variable ‘test3’ is declared but never used
int test4 = test2;         // Ok
//int test5 = test3;         // Error CS0165: Use of unassigned local variable ‘test3’

}

public static void Foo2() // static method
{

test1 = 2;

}

}

class Program
{

static void Main(string[] args)
{

            // Declaration only
            float temperature; // warning CS0168: The variable ‘temperature’ is declared but never used
            string name; // warning CS0168: The variable ‘name’ is declared but never used
            Test myClass; // The variable ‘myClass’ is declared but never used

            // Declaration with initializers 
            double limit = 3.5;
            int[] source = { 0, 1, 2, 3, 4, 5 };
            var query = from item in source
                        where item <= limit
                        select item;

Test.Foo2(); // Static method
// Test.Foo();  // Error CS0120: An object reference is required for the non-static field, method, or property 

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *