Wednesday, 4 June 2014

C# Tutorial-Basics- String Formatting

Building strings from variables is a very common task in programming. 
C# has the string.Format() method to format strings.
Some dynamic languages like Perl, PHP or Ruby support variable interpolation. 
Variable interpolation is replacing variables with their values inside string literals.
 C# does not allow this. It has string formatting instead.
using System;

public class StringFormatting
{
    static void Main()
    {
        int age = 34;
        string name = "Kshatriya";
        string output;

        output = string.Format("{0} is {1} years old.", 
            name, age);
        Console.WriteLine(output);
    }
}
Strings are immutable in C#.
We cannot modify an existing string. 
We must create a new string from existing strings and other types. 
In the code example, we create a new string. We also use values from two variables.

int age = 34;
string name = "Kshatriya";
string output;
Here we declare three variables.

output = string.Format("{0} is {1} years old.", 
    name, age);
We use the Format() method of the built-in string class. 
The {0}, {1} are the places where the variables are evaluated. 
The numbers represent the position of the variable. 
The {0} evaluates to the first supplied variable and the {1} to the second etc.
$ ./stringformatting.exe 
William is 34 years old.
This is the output of the stringformatting.exe program.

C# Tutorial-Basics-Constants

Unlike variables, constants retain their values. 
Once initialized, they cannot be modified. Constants are created with the const keyword.

using System;

public class Constants
{
    static void Main()
    {
        const int WIDTH = 100;
        const int HEIGHT= 150;
        int var = 40;

        var = 50;

        // WIDTH = 110;
    }
}

In this example, we declare two constants and one variable.

const int WIDTH = 100;
const int HEIGHT= 150;
We use the const keyword to inform the compiler, that we declare a constant. It is a convention to write constants in upper case letters.

int var = 40;

var = 50;
We declare and initialize a variable. Later, we assign a new value to the variable. It is legal.

// WIDTH = 110;
This is not possible with a constant. If we uncomment this line, we will get a compilation error.

C# Tutorial-Basics-Variables

variable is a place to store data. 
A variable has a name and a data type.
A data type determines, what values can be assigned to the variable. Integers, strings, boolean values etc. 
Over the time of the program, variables can obtain various values of the same data type. Variables are always initialized to the default value of their type before any reference to the variable can be made.

using System;

public class CSharpApp
{
    static void Main()
    {
        string city = "Chennai";
        string name = "Modi"; int age = 55;
        string nationality = "Indian";

        Console.WriteLine(city);
        Console.WriteLine(name);
        Console.WriteLine(age);
        Console.WriteLine(nationality);

        city = "Delhi";
        Console.WriteLine(city);
    }
}

In the above example, we work with four variables.

string city = "Chennai";
We declare a city variable of the string type and initialize it to the "Chennai" value.

string name = "Modi"; int age = 55;
We declare and initialize two more variables. We can put two statements into one line. But for readability reasons, each statement should be on a separate line.

Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);
We print the values of the variables to the terminal.

city = "Delhi";
We assign a new value to the city variable.
$ ./variables.exe 
Chennai
Modi
55
Indian
Delhi
This is the output of the example.

C# Tutorial-Basics-Command Line Arguments

C# programs can receive command line arguments. They follow the name of the program, when we run it.

using System;

public class CSharpApp 
{
    static void Main(string[] args) 
    {
        for (int i=0; i<args.Length; i++) 
        {
            Console.WriteLine("{0}", args[i]);
        }
    }
}

Command line arguments can be passed to the Main() method.

public static void Main(string[] args) 

This Main() method receives a string array of command line arguments.
for (int i=0; i<args.Length; i++) 
{
    Console.WriteLine("{0}", args[i]);
}

We go through the array of these arguments with a for loop and print them to the console. TheLength property gives the number of elements in the array. Loops and arrays will be described in more detail later.
$ ./commandargs.exe 1 2 3
1
2
3
We provide three numbers as command line arguments and these are printed to the console.

C# Tutorial-Basics-Reading Values

We can use the Console class to read values.

using System;

public class ReadLine
{
    static void Main()
    {
        string name;

        Console.Write("Enter your name: ");
        name = Console.ReadLine();
        Console.WriteLine("Hello {0}", name);
    }
}

The second program will read a value from a console and print it.

string name;
We declare a variable. The variable is called 'name'. 
Unlike constants, which store only one value during the life of the program, variables may store various different values of the same type. 
Thestring keyword defines the data type of the variable. Our variable will hold string values.

name = Console.ReadLine();
We read a line from the terminal. When we hit the Enter key, the input is assigned to the name variable.

Console.WriteLine("Hello {0}", name);
In this code line, we perform variable interpolation. 
Variable interpolation is replacing variables with their values inside string literals. Another names for variable interpolation are: variable substitution and variable expansion.
$ ./readline.exe 
Enter your name: Steve Jobs
Hello Steve Jobs
This is the output of the program.

C# Tutorial-Basics-simple program

In this part of the C# tutorial, we will cover basic programming concepts of the C# language. 
We will work with variables, constants and basic data types. We will read and write to the console; we will mention variable interpolation.
We start with a very simple code example.

using System;

public class Simple
{
    static void Main()
    {
        Console.WriteLine("This is C#");
    }
}

This is our first C# program. It will print "This is C#" message to the console. 

We will explain it line by line.
using System;
The using keyword imports a specific namespace to our program. Namespaces are created to group and/or distinguish named entities from other ones. This prevents name conflicts. This line is a C# statement. Each statement is ended with a semicolon.

public class Simple
{
    ...
}
Each C# program is structured. It consists of classes and its members.
A class is a basic building block of a C# program. 
The public keyword gives unrestricted access to this class. 
The above code is a class definition. The definition has a body, which starts with a left curly brace ({) and ends with a right curly brace (}).

static void Main()
{
    ...
}
The Main() is a method. A method is a piece of code created to do a specific job. 
Instead of putting all code into one place, we divide it into pieces, called methods. 
This brings modularity to our application.
 Each method has a body, in which we place statements. The body of a method is enclosed by curly brackets. 
The specific job for the Main() method is to start the application. It is the entry point to each console C# program. 
The method is declared to be static. This static method can be called without the need to create an instance of the CSharApp class. 
First we need start the application and after that, we are able to create instances of classes.

Console.WriteLine("This is C#");
In this code line, we print the "This is C#" string to the console. 
To print a message to the console, we use the WriteLine() method of the Console class. The class represents the standard input, output, and error streams for console applications. Note that Console class is part of the System namespace. 
This line was the reason to import the namespace with the using System; statement. 
If we didn't use the statement, we would have to use the fully qualified name of the WriteLine() method.
This would be System.Console.WriteLine("This is C#");.
$ ./simple.exe 
This is C#
Executing the program gives the above output.