#720 – Location of Declarations within A Method Does Matter
November 22, 2012 Leave a comment
When declaring members in a class, you can declare the members anywhere in the class, even placing a declaration after some code that references the declared member.
When you declare variables within a method, however, a variable must be declared before it is used. Compiling the code below will result in a compile-time error, since the leadin variable in the method RevealNames is declared after it is used.
public class Dog { public string Name { get; set; } public Dog(string name) { Name = name; secretName = "His Great Terribleness Mr. Bites-a-Lot"; } public void RevealNames() { Console.WriteLine(leadin); Console.WriteLine(string.Format("{0} is really {1}", Name, secretName)); string leadin = "Did you know?"; } private string secretName; }