Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0102 Assign value to local variable

C# requires that local variable must have assigned value. using System; class Program { static void Main(string[] args) { int i; Console.WriteLine(i); } } Compile the code above: Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. Program.cs(8,27): error CS0165: Use of unassigned local variable 'i' To fix the problem, assign a value to the local variable i. using System; class Program { static void Main(string[] args) { int i = 5; Console.WriteLine(i); } } We don't need to initialize each elements in an array explicitly, since array elements are initialized by C#.