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.
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
This would be
System.Console.WriteLine("This is C#");
.$ ./simple.exe This is C#
Executing the program gives the above output.
No comments:
Post a Comment