Lesson 1: Getting Started with C#






Getting Started with C#


This lesson will get you started with C# by introducing a few elementary programs. Here are the objectives of this lesson:
  • Understand the basic structure of a C# program.
  • Obtain a basic familiarization of what a “Namespace” is.
  • Obtain a basic understanding of what a Class is.
  • Learn what a Main method does.
  • Learn how to obtain command-line input.
  • Learn about console input/output (I/O).

A Simple C# Program

There are essential elements that all C# executable programs have, and that’s what we’ll concentrate on for this first lesson, starting off with a simple C# program. After reviewing the code in Listing 1-1, I’ll explain the basic concepts that will follow for all C# programs we will write throughout this tutorial. Please see Listing 1-1 to view this first program.
Warning: C# is case-sensitive.
Listing 1-1. A Simple Welcome Program: Welcome. cs
// Namespace Declaration
using System;

// Program start class
class WelcomeCSS
{
    // Main begins program execution.
    static void Main()
    {
        // Write to console
        Console.WriteLine("Welcome to the C# Station Tutorial!"); 
    }
}
The program in Listing 1-1 has 4 primary elements, a namespace declaration, a class, a Main method, and a program statement. It can be compiled with the following command line:
 csc.exe Welcome.cs
This produces a file named Welcome.exe, which can then be executed. Other programs can be compiled similarly by substituting their file name instead of Welcome. Cs. The file name and the class name can be totally different. For more help with command line options, type “CSC -help” on the command line.
Note for VS.NET Users: The screen will run and close quickly when launching this program from Visual Studio. NET. To prevent this, add the following code as the last line in the Main method:
// keep screen from going away
// when run from VS.NET
Console.ReadLine();
Note: The command line is a window that allows you to run commands and programs by typing the text in manually. It is often referred to as the DOS prompt, the operating system people used years ago, before Windows. The .NET Framework SDK, unrestricted, uses mainly command line tools. Therefore, I wrote this tutorial so that anyone could use it. Do a search through Windows Explorer for “csc.exe”, which is the C# compiler. When you know its location, add that location to your Windows path. Then open the command window by going to the Windows Start menu, selecting Run, and typing cmd.exe. This blog post might be helpful: How to set the path in Windows 7.
The first thing you should be aware of is that C# is case-sensitive. The word “Main” is not the same as its lowercase spelling, “main”. They are different identifiers. Coming from a language that is not case sensitive will trip you up several times until you become accustomed to it.
The namespace declaration, using System;, indicates that you are referencing the System namespace. Namespaces contain groups of code that can be called upon by C# programs. By using the System; declaration, you are telling your program that it can reference the code in the System namespace without pre-pending the word System to every reference. I’ll discuss this in more detail in Lesson 06: Namespaces, which is explicitly dedicated to namespaces.
class is one of a few different types of elements your program can use to describe objects, such as structsinterfacesdelegates, and enums, which will be discussed in more detail in Lesson 12: StructsLesson 13: InterfacesLesson 14: Delegates, and Lesson 17: Enums, respectively. The class declaration, class WelcomeCSS, contains the data and method definitions your program uses to execute. The class declaration, class WelcomeCSS, includes the data and method definitions your program uses to run. This particular class has no data, but it does have one method. This method defines the behaviour of this class (or what it is capable of doing). I’ll discuss types more in Lesson 07: Introduction to Classes. We’ll be covering a lot of information about courses throughout this tutorial.
The one method within the WelcomeCSS class tells what this class will do when executed. The method name, Main, is reserved for the starting point of a program. Main is often called the “entry point”, and if you ever receive a compiler error message saying that it can’t find the entry point, it means that you tried to compile an executable program without a Main method.
static modifier precedes the word Main, meaning that this method only works in this specific class rather than an instance of the course. This is necessary because when a program begins, no object instances exist. I’ll tell you more about classes, objects, and models in Lesson 07: Introduction to Classes.
Every method must have a return type. In this case, it is void, meaning Main does not return a value. Every technique has a parameter list following its Name with zero or more parameters between parentheses. For simplicity, we did not add parameters to Main. Later in this lesson, you’ll see what type of parameter the Main method can have. You’ll learn more about ways in Lesson 05: Methods.
The Main method specifies its behaviour with the Console.WriteLine(…) statement. The console is a class in the System namespace.WriteLine(…) is a method in the Console class. We use the “.” dot operator to separate subordinate program elements. Note that we could also write this statement as System.Console.WriteLine(…). This follows the “namespace.class.method” pattern as a fully qualified statement. Had we left out the using System declaration at the top of the program, it would have been mandatory for us to use the fully qualified form System.Console.WriteLine(…). This statement causes the string “Welcome to the C# Station Tutorial!” to print on the console screen.
Observe that comments are marked with “//”. These are single-line comments, meaning they are valid until the end-of-line. If you wish to span multiple lines with a comment, begin with “/*” and end with “*/”. Everything in between is part of the comment. Words are ignored when your program compiles. They are there to document what your program does in plain English (or the native language you speak daily).
All statements end with a “;” semi-colon. Classes and methods begin with “{“, left curly brace, and end with a “}”, right curly brace. Any statements within and including “{” and “}” define a block. Blocks define the scope (or lifetime and visibility) of program elements.

Accepting Command-Line Input

In the previous example, you simply ran the program, and it produced output. However, many programs are written to accept command-line input. This makes writing automated scripts that can invoke your program and pass information to it more accessible. If you look at many programs, including Windows OS utilities, that you use daily, most of them have some command-line interface. For example, if you type Notepad.exe MyFile.txt (assuming the file exists), then the Notepad program will open your MyFile.txt file so you can begin editing it. Also, you can make your programs accept command-put, as shown in Listings 1-2, which offers a program that agrees with a name from the command line and writes it to the console.
Danger! Even though I documented the proper use of command-line arguments before and after Listing 1-2, some people still email me to complain that they get an error or tell me there’s a bug in my program. In fact, I get more emails on this one subject than any other in the whole tutorial. Please read the instructions to include the command-line argument. <Smile />
Note: You must supply a command-line argument when running the NamedWelcome.exe application in Listing 1-2. For example, type the Name of the program followed by your Name: NamedWelcome YourName. Therefore, you must provide an argument on the command line for the program to work. The purpose of Listings 1-2 is to show you how to handle command-line input. If you are running Visual Studio, right-click on the project in Solution Explorer, select Properties, click the Debug tab, locate Start Options, and type your name into Command line arguments. If you forget to enter your name on the command line or enter it into the project properties, as I explained, you will receive an exception that says, “Index was outside the bounds of the array.” I didn't add exception handling to keep the program simple and concentrated only on handling command-line input. Besides, I haven’t taught you how to add exception handling to your program yet – but I will. In Lesson 15: Introduction to Exception Handling, you’ll learn more about exceptions and how to handle them properly.
Listing 1-2. Getting Command-Line Input: NamedWelcome.cs
// Namespace Declaration
using System;

// Program start class
class NamedWelcome
{
    // Main begins program execution.
    static void Main(string[] args)
    {
        // Write to console
        Console.WriteLine("Hello, {0}!", args[0]);
        Console.WriteLine("Welcome to the C# Station Tutorial!"); 
    }
}
Tip: Remember to add your name to the command line, i.e. “NamedWelcome Joe”. If you don’t, your program will crash. I’ll show you in Lesson 15: Introduction to Exception Handling how to detect and avoid such error conditions.
If you are using an IDE, like Visual Studio, see your IDE’s help documentation on how to set the command-line option via project properties. i.e. in Visual Studio 2010, double-click the Properties folder in your solution project, click the Debug tab and add your Name to Command Line Arguments. The primary step can/will differ between IDEs and versions, so please consult your IDE documentation for more information.
In Listing 1-2, you’ll notice an entry in the Main method’s parameter list. The parameter name is args, which you’ll use to refer to the parameter later in your program. The string[] expression defines the type of parameter that args is. The string type holds characters. These characters could form a single word or multiple words. The “[]” square brackets denote an Array, which is like a list. Therefore, the type of the args parameter is a list of words from the command line. Anytime you add string[] args to the parameter list of the Main method, the C# compiler emits code that parses command-line arguments and loads the command-line views into args. Reading arts allows you to access all discussions minus the application name typed on the command line.
You’ll also notice an additional Console.WriteLine(…) statement within the Main method. The argument list within this statement is different than before. It has a formatted string with a “{0}” parameter embedded in it. The first parameter in a formatted string begins at the number 0, the second is 1, and so on. The “{0}” parameter means that the following argument following the end quote will determine what goes in that position. Hold that thought, and now we’ll look at the following statement following the end quote.
The args[0] argument refers to the first string in the args array. The first element of an Array is number 0, the second is number 1, and so on. For example, if I typed NamedWelcome Joe on the command line, the value of args[0] would be “Joe”. This is a little tricky because you know that you typed NamedWelcome.exe on the command line. Still, C # doesn’t include the executable application name in the args list – only the first parameter after the executable application.
Returning to the embedded “{0}” parameter in the formatted string: Since args[0] is the first argument, after the formatted string, of the Console.WriteLine() statement, its value will be placed into the first embedded parameter of the formatted string. When this command is executed, the value of args[0], which is “Joe”, will replace “{0}” in the formatted string. Upon execution of the command line with “NamedWelcome Joe”, the output will be as follows:
Hello, Joe!
Welcome to the C# Station Tutorial!

Interacting via the Command-Line

Besides command-line input, another way to provide information to a program is via the Console. Typically, it works like this: You prompt the user for some information, they type something in and press the Enter key, and you read their report and take some action. Listings 1-3 show how to obtain interactive information from the user.
Listing 1-3. Getting Interactive Input: InteractiveWelcome.cs
// Namespace Declaration
using System;

// Program start class
class InteractiveWelcome
{
    // Main begins program execution.
    public static void Main()
    {
        // Write to console/get input
        Console.Write("What is your name?: ");
        Console.Write("Hello, {0}! ", Console.ReadLine());
        Console.WriteLine("Welcome to the C# Station Tutorial!"); 
    }
}
In Listing 1-3, the Main method doesn’t have any parameters — mainly because it isn’t necessary this time. Notice also that I prefixed the primary method declaration with the public keyword. The general keyword means that any class outside this one can access that class member. For Main, it doesn’t matter because your code would never call Main, but as you go through this tutorial, you’ll see how you can create classes with members that must be public so they can be used. The default access is private, meaning only members of the same type can access it. Keywords such as public and private are referred to as access modifiers. Lesson 19: Encapsulation discusses access modifiers in more depth.
There are three statements inside Main, and the first two differ from the third. They are Console.Write(…) instead of Console.WriteLine(…). The difference is that the Console.Write(…) statement writes to the Console and stops on the same line, but theConsole.WriteLine(…) goes to the next line after writing to the Console.
The first statement simply writes “What is your name?: ” to the Console.
The second statement doesn’t write anything until its arguments are properly evaluated. The first argument after the formatted string is Console.ReadLine(). This causes the program to wait for user input at the Console. After the user types input their Name, in this case, they must press the Enter key. The return value from this method replaces the “{0}” parameter of the formatted string and is written to the Console. This line could have also been written like this:
string name = Console.ReadLine(); 
Console.Write("Hello, {0}! ", name);
The last statement is written to the Console as described earlier. Upon execution of the command line with “InteractiveWelcome”, the output will be as follows:
>What is your name?  <type your name here> [Enter Key]
>Hello, <your name here>!  Welcome to the C# Station Tutorial!

Summary

Now you know the basic structure of a C# program. Using statements lets you reference a namespace and allows code to have shorter and more readable notation. The Main method is the entry point to start a C# program. You can capture command-line input when an application is run by reading items from a string[] (string array) parameter to your Main method. Interactive I/O can be performed with the Console class's Readline, Write, and WriteLine methods.
This is just the beginning, the first of many lessons. I invite you to take Lesson 2: Operators, Types, and Variables.

Post a Comment

0 Comments