Book Image

Learn C# Programming

By : Marius Bancila, Raffaele Rialdi, Ankit Sharma
5 (1)
Book Image

Learn C# Programming

5 (1)
By: Marius Bancila, Raffaele Rialdi, Ankit Sharma

Overview of this book

The C# programming language is often developers’ primary choice for creating a wide range of applications for desktop, cloud, and mobile. In nearly two decades of its existence, C# has evolved from a general-purpose, object-oriented language to a multi-paradigm language with impressive features. This book will take you through C# from the ground up in a step-by-step manner. You'll start with the building blocks of C#, which include basic data types, variables, strings, arrays, operators, control statements, and loops. Once comfortable with the basics, you'll then progress to learning object-oriented programming concepts such as classes and structures, objects, interfaces, and abstraction. Generics, functional programming, dynamic, and asynchronous programming are covered in detail. This book also takes you through regular expressions, reflection, memory management, pattern matching, exceptions, and many other advanced topics. As you advance, you'll explore the .NET Core 3 framework and learn how to use the dotnet command-line interface (CLI), consume NuGet packages, develop for Linux, and migrate apps built with .NET Framework. Finally, you'll understand how to run unit tests with the Microsoft unit testing frameworks available in Visual Studio. By the end of this book, you’ll be well-versed with the essentials of the C# language and be ready to start creating apps with it.
Table of Contents (20 chapters)

Variables

Variables are defined as a named memory location that can be assigned to a value. There are several types of variables, including the following:

  • Local variables: These are variables that are defined within a method and their scope is local to that method.
  • Method parameters: These are variables that hold the arguments passed to a method during a function call.
  • Class fields: These are variables that are defined in the scope of the class and are accessible to all of the class methods and depending on the accessibility of the field to other classes too.
  • Array elements: These are variables that refer to elements in an array.

In this section, we will refer to local variables, which are variables declared in the body of a function. Such variables are declared using the following syntax:

datatype variable_name;

In this statement, datatype is the data type of the variable and variable_name is the name of the variable. Here are several examples:

bool f;
char ch = 'x';
int a, b = 20, c = 42;
a = -1;
f = true;

In this example, f is an uninitialized bool variable. Uninitialized variables cannot be used in any expression. An attempt to do so will result in a compiler error. All variables must be initialized before they are used. A variable can be initialized when declared, such as with ch, b, and c in the preceding example, or at any later time, such as with a and f.

Multiple variables of the same type can be declared and initialized in a single statement, separated by a comma. This is exemplified in the preceding code snippet with the int variables a, b, and c.

Naming convention

There are several rules that must be followed for naming a variable:

  • Variable names can consist of letters, digits, and underscore characters (_) only.
  • You cannot use any special character other than underscore (_) when naming a variable. Consequently, @sample, #tag, name%, and so on are illegal variable names.
  • The variable name must begin with a letter or an underscore character (_). The name of the variable cannot start with a digit. Therefore, 2small as a variable name will throw a compile-time error.
  • Variable names are case-sensitive. Therefore, person and PERSON are considered two different variables.
  • A variable name cannot be any reserved keyword of C#. Hence true, false, double, float, var, and so on are illegal variable names. However, prefixing a keyword with @ enables the compiler to treat them as identifiers, rather than keywords. Therefore, variables names such as @true, @return, @var are allowed. These are called verbatim identifiers.
  • Apart from the language rules that you must follow when naming variables, you should also make sure the names you choose are descriptive and easy to understand. You should always prefer that over short, abbreviated names that are hard to comprehend. There are various coding standards and naming conventions and you should adhere to one. These promote consistency and make the code easier to read, understand, and maintain.

When it comes to naming conventions, you should do the following when programming in C#:

  • Use pascal case for classes, structures, enums, delegates, constructors, methods, properties, and constants. In Pascal case, each word in a name is capitalized; examples include ConnectionString, UserGroup, and XmlReader.
  • Use camel case for fields, local variables, and method parameters. In camel case, the first word of a name is not capitalized, but all of the others are; examples include userId, xmlDocument, and uiControl.
  • Do not use underscore in identifiers unless to prefix private fields, such as in _firstName, and_lastName.
  • Prefer descriptive name over abbreviations. For example, prefer labelText over lbltxt or employeeId over eid.

You can learn more about coding standards and naming conventions in C# by consulting additional resources.

Implicity-typed variables

As we have seen in previous examples, we need to specify the type of a variable when we are declaring it. However, C# provides us with another way to declare variables that allows the compiler to infer the variable type based on the value assigned to it during initialization. These are known as implicitly typed variables.

We can create an implicitly typed variable using the var keyword. Such variables must always be initialized on the declaration because the compiler infers the type of the variable from the value that it is initialized with. Here is an example:

var a = 10;

Since the a variable is initialized with an integer literal, a is considered as an int variable by the compiler.

When declaring variables with var, you must keep in mind the following:

  • An implicitly typed variable must be initialized to a value at the time of declaration, otherwise, the compiler has no reference to infer the variable type and it results in a compile-time error.
  • You cannot initialize it to null.
  • The variable type cannot be changed once it is declared and initialized.

    Information box

    The var keyword is not a datatype but a placeholder for an actual type. Using var to declare variables is useful when the type name is long and you want to avoid typing a lot (for example, Dictionary<string, KeyValuePair<int, string>>) or you do not care about the actual type, only the value.

Now that you learned how you can declare variables, let's look at a key concept: the scope of variables.

Understanding the scope and lifetime of variables

A scope in C# is defined as a block between an opening curly brace and its corresponding closing curly brace. The scope defines the visibility and lifetime of a variable. A variable can be accessed only within the scope in which it is defined. A variable that is defined in a particular scope is not visible to the code outside that scope.

Let's understand this with the help of an example:

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i < 10; i++)
        {
            Console.WriteLine(i);
        }
        i = 20; // i is out of scope
    }
}

In this example, the i variable is defined inside the for loop, hence it cannot be accessed outside the for loop as it goes out of scope once the control exits the loop. You will learn more about the for loop in the next chapter.

We can also have nested scopes. This means a variable defined in a scope can be accessed in another scope that is enclosed in that scope. However, the variables from the outer scope are visible to the inner scope but the inner scope variables are not accessible in the outer scope. The C# compiler won't allow you to create two variables with the same name within a scope.

Let's extend the code in the previous example to understand this:

class Program
{
    static void Main(string[] args)
    {
        int a = 5;
        for (int i = 1; i < 10; i++)
        {
            char a = 'w';                 // compiler error
            if (i % 2 == 0)
            {
                Console.WriteLine(i + a); // a is within the 
                                          // scope of Main
            }
        }
        i = 20;                           // i is out of scope
    }
}

Here, the integer variable a is defined outside the for loop but within the scope of Main. Hence, it can be accessed within the for loop as it is in the scope of this. However, the i variable, which is defined inside the for loop, cannot be accessed inside the scope of Main.

If we try to declare another variable with the same name in the scope, we will get a compile-time error. Consequently, we cannot declare a character variable a inside the for loop as we already have an integer variable with the same name.