#964 – Declaring a Variable within a Block of Statements

When you declare a block of statements in your code, you can declare variables within that block that will have a scope that is local to the block.  This is, the variable will be visible only to other code within the block.

This is most often done within a function:

        static void DoSomething()
        {
            // Variable local to this function
            string name = "Bob";

            Console.WriteLine(name);
        }

You can, however, declare local variables within any block of statements.

            if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday)
            {
                string bestFood = "Pizza";
                Console.WriteLine(bestFood);
            }

            // Can't access bestFood variable out here
Advertisements

#963 – Use Braces to Enclose a Block of Statements

block of statements in C# is a series of individual statements enclosed by a set of curly braces ({, }).  You can typically include a block of statements wherever a single statement is expected.

            // Single statement follows if
            if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
                Console.WriteLine("Getting to work");

            // Block of statements follows if
            if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
            {
                Console.WriteLine("Making pancakes");
                Console.WriteLine("Washing my socks");
                Console.WriteLine("Mowing the lawn");
            }

Although far less common, you can also include a block of statements to arbitrarily group a set of statements within a longer sequence of statements.

            Console.WriteLine("Reading Edith Wharton");

            {
                Console.WriteLine("Eating lunch");
                Console.WriteLine("Washing my hands");
            }

            Console.WriteLine("Studying Byzantium");

963-001

#962 – Statements Can Span Multiple Lines

Single statements in C# (as opposed to a block of statements enclosed in curly braces) are typically written on a single line and terminated by a semicolon.

The code fragment below contains two statements, one that initializes an instance of a Dog and one that invokes the Bark method on that instanceEach of the statements is terminated by a semicolon.

Dog d1 = new Dog("Jack", 17);
d1.Bark("Yip", 4);

You can break a statement into as many lines as you like in your source code, as long as you don’t insert a line break in the middle of an identifier. The code fragment below splits the two statements above into several lines.

            Dog d1
                = new Dog(
                    "Jack",    // Name
                    17);       // Age
            d1.Bark(
                "Yip",     // Bark sound
                4);        // # times to bark

#961 – Retrieving Command Line and Path to Executable

You can easily get information about the full command used to launch your application, as well as the path to the executable containing your code.

  • Environment.CommandLine is a string containing the full command line that launched your application
  • Environment.CurrentDirectory is a string containing the full path to the current working directory (which may be different from the directory containing your application)
  • Assembly.GetExecutingAssembly().CodeBase is a string containing the full path to the executable or DLL containing the code that is currently executing

For example:

            Console.WriteLine("Your full command line was:");
            Console.WriteLine(string.Format("  {0}", Environment.CommandLine));

            Console.WriteLine("Current working directory is:");
            Console.WriteLine(string.Format("  {0}", Environment.CurrentDirectory));

            // Requires: using System.Reflection;
            Console.WriteLine("Full path to executable:");
            Console.WriteLine(string.Format("  {0}", Assembly.GetExecutingAssembly().CodeBase));

If we launch the application as follows:
961-001
We’ll see the following output:
961-002

#960 – Conventions for Naming Classes

Below are the typical conventions used when naming classes:

  • Use PascalCasing
    • Capitalize first letter of each word
    • Capitalize only first letter of 3+ letter acronyms
  • Use a singular noun or noun phrase
  • Don’t use underscores
  • Don’t use abbreviations
  • Don’t prefix the name with any special character (e.g. CPerson)

Here are some examples of class names that follow these guidelines:

  • LogFile
  • Book
  • BookChapter
  • ComplexNumber

#959 – Don’t Use Double Underscores at the Start of an Identifier

When naming identifiers in C#, you can use the underscore (‘_’) character anywhere in the identifier name, including at the beginning of the name.

Some people use identifiers that begin with a single underscore for private fields (e.g. _name_age).  This use is no longer recommend.  You should instead just use camelCasing for private fields.  If you want to make clear that the identifer is a member variable, you can use the this keyword (e.g. this.namethis.age).

You should, however, never use a double underscore at the start of an identifier name.  There are already several reserved keywords that start with a double underscore (e.g. __reftype, __refvalue).  The double underscore notation is meant to be used for these reserved keywords and future revisions to C# may add new keywords that may then conflict with any identifiers that you have in your code.

#958 – Naming Conventions for Identifiers

By convention, readable C# code typically uses some naming convention for identifiers in the code.

Identifiers in your code include:

  • Type names (class, struct, interface, delegate, enum)
  • Class members (methods, properties, constants, fields, events)
  • Local variables

Recommended rules for identifier naming:

  • Limit to alphanumeric (e.g. ‘a’..’z’, ‘A’..’Z’, ‘0’..’9′)
  • Begin identifier with an alphabetic character
  • No abbreviations within identifier
  • Longer identifiers are typically more clear (within reason)

Identifiers should use either PascalCasing or camelCasing:

  • PascalCasing
    • Capitalize first letter of each word
    • Capitalize only first letter of 3+ letter acronyms
    • e.g. MyLogFileWriter
  • camelCasing
    • Capitalize first letter of all but first word
    • First letter of first word is lowercase
    • Capitalize only first letter of 3+ letter acronyms
    • e.g. pathToLogFile

Recommended:

  • PascalCasing for
    • Type Names  (but prefix interfaces with ‘I’)
    • Methods, Properties, Constants, Events, and public Fields
  • camelCasing for
    • Private fields, local variables, and method parameters