Variables =========== These names associated with a data storage location are called *variables*. In other words, variables represent the locations of objects in memory. Some general rules for C# variables are: - Every variable has a **type** that determines what values can be stored in the variable. - The C# compiler guarantees that values stored in variables are always of the appropriate type. - The value of a variable can be changed through **assignment** or through use of the ++ and -- operators. - Variables are either initially assigned or initially unassigned. Variables can have local scope or global scope: - Local variables are declared within a method and can only be accessed within that method. - Global variables typically refer to static fields that are accessible throughout the class. Declaring Local Variables --------------------------- A declaration statement declares a new local variable, local constant, or local reference variable. To declare a local variable, specify a type and provide a variable name. You can declare multiple variables of the same type in one statement: ``type variableName;`` In this syntax, - **type** is a C# type (such as int or string), - **variableName** is the name of the variable (such as x or name) - the semicolon ``;`` is the statement terminator. For example, you may declare the following variables .. code-block:: string greeting; // declaring one string variable int a, b, c; // declaring multiple int variables List xs; // a reference type (double list) variable You can also provide initial values when declaring a variable. The syntax is:: type variableName = value; For example, .. code-block:: string greeting = "Hello"; int a = 3, b = 2, c = a + b; List xs = new(); In this syntax, - the equal sign ``=`` is the assignment operator (note that it is not the equal sign in mathematics) The ``var`` Keyword --------------------- Local variables can be declared without giving an explicit type. The complier will then infer the type of a variable from its initialization expression. The keyword ``var`` is used in case of this. For example:: var greeting = "Hello"; Console.WriteLine(greeting.GetType()); // output: System.String var a = 100; Console.WriteLine(a.GetType()); // output: System.Int32 var xs = new List(); Console.WriteLine(xs.GetType()); // output: System.Collections.Generic.List`1[System.Double] Assignment Statements -------------------------- If you need to change the value to a variable, you need to use the **assignment statement**. Note that an assignment statement is read from right to left. For example, if we create a variable "area" and assign the value of "width * height" to it like:: area = width * height; The assignment statement starts by evaluating the **expression** on the right-hand side: ``width * height``. Since width * height is an expression, the expression will be evaluated to a value like when evaluating an expression in math, so the values are substituted as .. code-block:: none 5 * 7 which is then evaluates to 35 and finally assigned to the variable, ``area``, on the left. The whole block of code could look something like follows. You may notice that we are operating with three variables here. .. code-block:: none > int width = 5, height, area; > height = 7; > area = width * height; > area 35 In the example above, ``width * height``, as an expression, evaluates to a value; while ``int width = 5, height, area;`` is a declaration statement and ``height = 7;`` an assignment statement. You should also notice that the value of the most *recent* assignment is remembered until reassigned. Also, it is common to use the same variable name when we intend to change the value to the variable without keeping the previous value, and after the initial declaration you don't need to declare type anymore:: int a = 10; a = 100; // reassignment To further illustrate how expression and statement work in C#, or in programming languages in general, we can take a look at the example as follows. In this case, we are making two assignment statements: one with a literal value and one with an expression:: > int n = 7; > n = n + 1; > n 8 In short piece of code above, we have an initial assignment statement (``n = 7``), a variable reassignment (``n = n + 1``) involving an expression ``n + 1``, and finally the *new* value of ``n`` is 8, replacing the old 7. ** note that we are using a REPL and that is why we are able to type the variable name and hit Enter to see the value. Variable, Identifiers, and Literals ----------------------------------------- In programming languages, an **identifier** is defined as the name assigned to a entity (class, interface, struct, delegate, or enum), member, *variable*, function, method, or namespace, etc. A variable is an identifier/name assigned to a memory location that stores a value or object reference. **Literals**: Expressions with straight values such as ``7`` or ``1.23`` or ``"hello"`` are called *literals* because they *literally* represent what they are. For example: - A ``bool`` variable has two literal values: true or false. - A string literal is a series of characters delimited by double quotes in one line. - An integral numeric type can have three kinds of literals: decimal, hexadecimal, and binary. Naming Convention of Identifiers --------------------------------- Some of the common conventions [#]_ to follow when naming C# identifiers are: - The characters must all be letters, digits, or underscores ``_``, and must start with a letter. .. - *Reserved keywords* may not be used to name your own identifiers unless a ``@`` is prefixed. Common IDE's will be able to catch this. - C# is case sensitive: The identifiers ``name``, ``NAME``, and ``NaMe`` are different. - By convention, C# programs use **PascalCase** for namespace, class, and method names and **camelCase** for **variable** and method parameters. [#]_ - Use meaningful and descriptive names for variables, methods, and classes. - Avoid keywords when naming identifiers. Keywords ----------- .. index:: keyword Keywords are predefined, reserved *identifiers* that have special meanings to the compiler and can not be used as identifiers (including variable names) in your program unless they include @ as a prefix. Current **reserved keywords** are as the table blow. You can see that many of the data type names are reserved keywords. ========== ========== ========== ========== ========== abstract do in protected true as double int public try base else interface readonly typeof bool enum internal ref uint break event is return ulong byte explicit lock sbyte unchecked case extern long sealed unsafe catch false namespace short ushort char finally new sizeof using checked fixed null stackalloc virtual class float object static void const for operator string volatile continue foreach out struct while decimal goto override switch default if params this delegate implicit private throw ========== ========== ========== ========== ========== C# has another set of keywords called contextual keywords that are keywords with special meaning in specific context and may be used as identifiers outside the program context. .. rubric:: Footnotes .. [#] For C# identifier naming conventions, see: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names. Also, for coding conventions, see https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions#style-guidelines. .. [#] There are also snake_case, commonly used in Python, and kebab-case, commonly used in CSS.