Basics
In this part of the C# tutorial, we will cover basic programming concepts of the C# language. We introduce the very basic programs. 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;This is our first C# program. It will print "This is C#" message to the console. We will explain it line by line.
public class CSharpApp
{
static void Main()
{
Console.WriteLine("This is C#");
}
}
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 CSharpAppEach 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.exeExecuting the program gives the above output.
This is C#
Reading values We can use the Console class to read values as well.
using System;The second program will read a value from a console and print it.
public class CSharpApp
{
static void Main()
{
string name;
Console.Write("Enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Hello {0}", name);
}
}
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. The
string
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 interpolationis replacing variables with their values inside string literals. Another names for variable interpolation are: variable substitution and variable expansion.
$ ./readline.exeThis is the output of the second program.
Enter your name: Jan Bodnar
Hello Jan Bodnar
Command line arguments
C# programs can receive command line arguments. They follow the name of the program, when we run it.using System;Command line arguments can be passed to the Main() method.
public class CSharpApp
{
static void Main(string[] args)
{
for (int i=0; i<args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
}
}
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++)We go through the array of these arguments with a for loop and print them to the console. The
{
Console.WriteLine("{0}", args[i]);
}
Length
property gives the number of elements in the array. Loops and arrays will be described in more detail later. $ ./commandargs.exe 1 2 3We provide three numbers as command line arguments and these are printed to the console.
1
2
3
In C# 2008 Express Edition, select project properties. In the Debug tab, there is a text area for specifying the command line arguments.
Figure: Command line arguments
Variables and Constants
A 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. Unlike variables, constants retain their values. Once initialized, they cannot be modified. Constants are created with the const keyword.using System;In the above example, we work with four variables.
public class CSharpApp
{
static void Main()
{
string city = "New York";
string name = "Paul"; int age = 35;
string nationality = "American";
Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);
city = "London";
Console.WriteLine(city);
}
}
string city = "New York";We declare a city variable of the string type and initialize it to the "New York" value.
string name = "Paul"; int age = 35;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);We print the values of the variables to the terminal.
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);
city = "London";We assign a new value to the city variable.
$ ./variables.exeOutput of the example.
New York
Paul
35
American
London
Constants As we already said above, constants cannot change their initial values.
using System;In this example, we declare two constants and one variable.
public class CSharpApp
{
static void Main()
{
const int WIDTH = 100;
const int HEIGHT= 150;
int var = 40;
var = 50;
// WIDTH = 110;
}
}
const int WIDTH = 100;We use the
const int HEIGHT= 150;
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;We declare and initialize a variable. Later, we assign a new value to the variable. It is legal.
var = 50;
// WIDTH = 110;This is not possible with a constant. If we uncomment this line, we will get a compilation error.
Variable interpolation
Variable interpolation is replacing variables with their values inside string literals. Another names for variable interpolation are: variable substitution and variable expansion.using System;In C#, strings are immutable. We cannot modify an existing string. Variable interpolation happens during string creation.
public class CSharpApp
{
static void Main()
{
int age = 34;
string name = "William";
string output;
output = string.Format("{0} is {1} years old.",
name, age);
Console.WriteLine(output);
}
}
int age = 34;Here we declare three variables.
string name = "William";
string output;
output = string.Format("{0} is {1} years old.",We use the
name, age);
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. {0} evaluates to the first supplied variable, {1} to the second etc. $ ./interpolation.exeOutput.
William is 34 years old.
This chapter covered some basics of the C# language.
0 comments:
Post a Comment