Visual C# Fundamentals - Lesson 1: Introduction to C#
 
Home

Introduction to C#

 

Introduction

 

Overview of C#

C#, pronounced c sharp, is a computer language used to give instructions that tell the computer what to do, how to do it, and when to do it. This is a universal language that, although currently mostly used on the Microsoft Windows operating system, will be also used on other operating systems like Linux, BeOS, Macintosh, etc. C# is one of the languages used in the Microsoft .NET Framework. The Microsoft .NET Framework is a library of objects that create or draw things on the computer.

The C# language is used to create applications that display on a black window referred to as the DOS prompt or DOS window.

Introduction to Objects

An object, any object, is made of different parts. For example, a car is made of tires, doors, wires, belts, etc:

Car

In computer languages, such an object is called a class.

In the C# language, everything is built as a class. Therefore, a program starts with the class keyword followed by a name. Here is an example:

class Car

The actual building of a class starts with an opening curly bracket "{" and ends with a closing curly bracket "}". Therefore, a class can be created as follows:

class Car { }

Because a class can be made of numerous parts, such as tires, doors, seats, etc, listed as sub-objects of a class, one line could become (too) crowded. Therefore, each curly bracket should be displayed on its own line:

class Car
{
}

The assignments of a program written in C# are carried in entities called methods. A method is simply a section of code that takes care of a particular detail for the functionality of the program. To create a method, you must specify its name, which starts with a letter or an underscore and can be followed by letters, digits, or underscores. The name of a method is followed by an opening and a closing parentheses. Here is an example:

class Car
{
Drive()
}

A method's job is to carry a specific assignment within a program. As such, it could provide a value once the assignment has been carried. In Lesson 8, we will review the types of values that a method can provide. If on the other hand a method doesn't give back a value, then it is considered void. The type of value that a method can provide (or return) is written on the left side of the method name. An example would be:

class Car
{
void Drive()
}

The assignment that a method carries is included between an opening curly bracket "{" and a closing curly bracket "}". Therefore, a method can be written as follows:

class Car
{
void Drive()
{
}
}

Indentation is a technique of specifying where a line of code starts and where it ends. Although indentation is not part of the C# language, it makes the program easier to read. Therefore, the above lines of code can be written as follows:

class Car
{
	void Drive()
	{
	}
}

Note that this time, it is easier to know where the class starts and ends, and where the method starts and ends. In some occasions (we will see when and why), we will need to write a method as "static".

The most regularly used method of a C# program is called Main. Therefore, the minimum you can write a program with, is as follows:

class Car
{
	static void Main()
	{
	}
}

A computer program is started in a regular computer file. A file for a C# program has the extension .cs. To make your programming fast, the C# language ships with many primary files that allow you to lay a foundation for your program.

 

Command Line Fundamentals

 

Introduction

When the computer starts, there is no primary visual or graphical effect. The programs must first be loaded into memory. In fact, in the beginning, the Microsoft operating system started as text-based with DOS 2.2, 3.3, 5.0, and 6.2 (6.2 was never a big hit like 5.0 because Windows 3.1, Windows 3.2, and Windows 3.3 was released at the same time, bringing the now attractive "Windows" display). To create a program, a programmer entered the source code using a text editor (there was a text editor called EDIT; it was very cute, very basic, and very wonderful; in fact, up to Windows 3.3, it was still the text editor of choice of most programmers and it was used as the editor for QBasic, the parent of Visual Basic). After creating the source file, the programmer had to use a black (or "amber") screen that displayed a blinking caret whose role was to let the user know that it was waiting for a command.

A command was a word or a group of words that the programmer typed and pressed Enter (or Return). This caused the computer to produce an action. The command was typed on a line. For this reason, the area that displayed the caret was called the Command Line. Most low-level (low-level doesn't mean weak, to the contrary) programs are still using this concept. This means that, behind the scenes, computer languages such as C/C++, Pascal, Java, C#, etc, are still created and executed as if things were done at the Command Line.

 

Command Line Understanding

To be an effective programmer, it is important to know how the Command Line works because, as mentioned already, C# programs are compiled at the Command Prompt. If you know how the Command Line works, you can have a better understanding of things that are going on behind the scenes.

As its name indicates, the Command Line is a blank line with a blinking caret that expects you to type a command:

There are various types of commands used on the command prompt. Some of them are as old as the operating system. Such is the case for commands used to create files or folders, copy files or folders, delete files or folders, format a drive, etc. Some other commands are created by a person like you who needs it for a particular application. For example, the C# language provides a command called csc to compile a program at the command line. In the same way, when you create a program, particularly when you create a source file, you can use some options that would be used at the command prompt.

The Compiler

You may have realized that all of the words we have used so far, such as class, void, or static, are regular English words that you can read and whose meaning you can find in a dictionary. Computer languages are created with meaningful words like that to make them easier to read and understand. Unfortunately, the computer doesn't understand those words and cannot execute the instructions those words represent. Like most other languages, C# is just a language that is used to give instructions to the computer. To make the computer understand these instructions, you need another, somehow more powerful, program. This program would receive the language's instructions in plain English and "translate" them in another language that the computer can understand. This program is called a compiler.

A compiler is a computer program made of internal other sub-programs. One of the sub-programs, in fact probably the first, of a compiler is called a parser. A parser "scans" a file that contains (part of) the program. It checks for syntax, keywords, unknown words, and some other routines. If the parser finds a problem, which could be anything, either it stops or it continues making a list of the mistakes it found. Then it displays this list to you to fix. Sometimes it would point to the exact line where the/a problem was found. Sometimes it would point to the line where the problem showed its impact although the problem may be found somewhere else. With experience, you will know how to fix the programs or troubleshoot these problems. On this site, we will address as many issues as possible.

If the parser doesn't find any problem, or after you have fixed the problems, it (the parser) passes its result(s) to the compiler. The compiler calls another program called a linker. If the program contains just one file, the linker considers it. If the program contains more than one file (because a program can contain as many files as necessary), the linker considers them. The linker gathers some of the files that the C# compiler shipped with (those files that your program needs in order to work, since your program doesn't need all possible files that C# ships with), puts them together ("links" them) with your file(s) to get your instructions in a manner that can produce a suitable result. If there is no significant problem, the compiler creates the program. This doesn't mean that everything is alright, it only means that the compiler thinks that everything is alright: it is still possible that the result may not be what you would expect. To make your life easier, all of the sub-programs (parser, linker, debugger, etc) that ship with C# are grouped in one large program: the compiler. Therefore, from now on, we will use the word "compiler" to refer to the program you use to "translate" your English-based instructions into a computer-based language.

The compiler that ships with the C# version we will use, that is, the compiler of the .NET Framework is a program called csc. Like most other programs, it has the extension .exe. This csc name is not standard. This means that another C# compiler may have another name; csc.exe is just the name of the compiler we will use.

 
 

Creating a Program

On this site, we will use Microsoft Visual Studio .NET to create our programs. To use it, you have two main options. You can start from an empty project and add the necessary files, or you can create a console application using its Option.

 

Practical LearningPractical Learning: Creating a Program

  1. Start Microsoft Visual C# or Visual Studio .NET
  2. On the main menu, click File -> New -> Project
  3. If necessary, in the Project Types list of the New Project dialog box, click Visual C# Projects
  4. In the Templates list, click Empty Project
  5. In the Name text box, replace the name with Exercise1 and specify the desired path in the Location
     
  6. Click OK
  7. To create a source file for the project, on the main menu, click Project -> Add New Item...
  8. In the Add New Item dialog box, in the Templates list, click Code File
  9. In the Name text box, delete the suggested name and replace it with Exercise
     
  10. Click Open
  11. In the empty file, type the following:
     
    class OrderProcessing
    {
    	static void Main()
    	{
    	}
    }
  12. To save the file, on the main menu, click File -> Save
  13. To execute the application, on the main menu, click Debug -> Start Without Debugging
     
  14. Press Enter to close the DOS window and return to Visual C#
 

Namespaces

 

Introduction

When many people work in creating the same program, it could be difficult to keep track of the names of various classes. If more than one programmer creates a class with the same name in the same program, there would be conflict and the program would not work. The solution to avoid this situation is to delimit sections of code with names.

A namespace is a section of code that is identified by a specific name. The name could be anything such as somebody's name, the name of the company's department, or a city. To create a namespace, you start with the namespace keyword followed by the name of the section.

Like a class, the section that is part of a namespace starts with an opening curly bracket "{" and ends with a closing curly bracket "}". Here is an example:

namespace Jason
{
}

Between the curly brackets, you can type anything that is part of the namespace. For example, you can create a class inside of a namespace. Here is an example:

namespace Jason
{
	class Airport
	{
	}
}
 

Practical LearningPractical Learning: Creating a Namespace

  1. To create a namespace, change the file as follows:
     
    namespace GeorgetownCleaners
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    		}
    	}
    }
  2. Save the file
 

Accessing Members of a Namespace

After creating the necessary items in a namespace, you can use the period operator to access an item that is part of the namespace. To do this, in the desired location, type the name of the namespace, followed by a period, followed by the desired member of the namespace. Here is an example:

namespace Accounting
{
	class Departure
	{
	}
}

class MainClass
{
	static void Main()
	{
		Accounting.Departure
	}
}
 

Namespace Nesting

Imagine that you create a namespace called Accounting and many people from the Accounting department are asked to create their methods and objects only in the Accounting namespace and you may have asked the Accounting programmers not to create their methods and objects outside of the Accounting namespace. One thing you can do is to create other namespaces inside of the existing namespace.

Creating a namespace inside of an existing namespace is referred to as nesting the namespace. The namespace inside of another namespace is nested.

To create a namespace inside of another, simply type it as you would create another namespace. Here is an example:

namespace Accounting
{
	namespace Jason
	{
	}
}

In the example above, the Jason namespace is nested inside of the Accounting namespace.

After creating the needed namespaces, nested or not, you can create the necessary methods and objects inside of the desired namespace. To access anything that is included in a nested namespace, you use the period operator before calling a member of a namespace or before calling the next nested namespace. Here is an example:

namespace Accounting
{
	class Payroll
	{
	}
}
namespace Personnel
{
	namespace EmployeesRecords
	{
		class TimeSheet
		{
		}
	}
	namespace Benefits
	{
		class MedicalInsurance
		{
		}
	}
}

class MainClass
{
	static void Main()
	{
		Accounting.Payroll
		Personnel.Benefits.MedicalInsurance
		Personnel.EmployeesRecords.TimeSheet
	}
}

A line of code such as Accounting.Payroll is called a statement. Every statement must be terminated with a colon. Therefore, this statement may be written as:

Accounting.Payroll;
 

The System Namespace

 

Introduction

To make programming in C# a little easier, many classes have already been created and stored in various namespaces. Each namespace in C# is used to provide a specify set of classes. The most regularly used namespace in the C# language is called System. Inside of the System namespace is a class called Console. The Console class is used to display things on the console screen also called the DOS window.

The Console class contains assignments (called methods) to display information on the screen or to retrieve information from the user who types it in the DOS window. The method that is used to display text on the screen is called Write. To use the Write() method, inside of the parentheses, type the sentence between double-quotes. Here is an example:

class Program
{
	static void Main()
	{
		System.Console.Write("The Wonderful World of C# Programming");
	}
}

Besides the Write() method, the Console class also provides a method called WriteLine(). The difference is that, after displaying something on the screen, the Write() method keeps the caret on the same line but WriteLine() transfers the caret the next line. We will see various examples of this behavior throughout our lessons.

 

Practical LearningPractical Learning: Introducing Console Methods

  1. To use the System namespace, change the contents of the file as follows:
     
    namespace GeorgetownCleaners
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			System.Console.WriteLine("Georgetown Cleaning Services");
    		}
    	}
    }
  2. Execute the application again to see the result
     
  3. Press Enter to close the window and return to Visual C#
 

The Using Keyword

We saw that, to call an object or a method that is part of a namespace, you must "qualify" that method or object using the period operator. Instead of using this approach, if you already know the name of a namespace that exists or has been created in another file, you can use a special keyword to indicate that you are using a namespace that is defined somewhere. This is done with the using keyword. To do this, on top of the file (preferably), type using followed by the name of the namespace.

With the using keyword, you can include as many external namespaces as necessary.

 

Practical LearningPractical Learning: Using the Keyword

  1. Change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaners
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			Console.WriteLine("Georgetown Cleaning Services");
    		}
    	}
    }
  2. Execute the application to test it
  3. Return to Visual C#
  4. To create an application using a wizard, on the main menu, click File -> New -> Project
  5. In the Project Types list of the New Project dialog box, make sure Visual C# Projects is selected.
    In the Templates list, click Console Application
  6. In the Name text box, replace the name with Exercise2 and specify the desired path in the Location
     
  7. Click OK
  8. To change the name of the file, in Solution Explorer, right-click Class1 and click Rename
  9. Type Exercise.cs and press Enter
  10. To rename the class, in the Code Editor, double-click Class1 and type OrderProcessing
  11. Execute the application
 

Accessories for Coding

 

Comments

A comment is a line or paragraph of text that the compiler would not consider when examining the code of a program. There are two types of comments recognized by C#.

To display a comment on a line of text, start the line with two forward slashes //. Anything on the right side of // would be ignored. Here is an example:

// This line will be ignored. I can write in it anything I want

The above type of comment is used on only one line. You can also start a comment with /*. This type of comment ends with */. Anything between this combination of /* and */ would not be read by the compiler. Therefore, you can use this technique to span a comment on more than one line.

 

Practical LearningPractical Learning: Creating Comments

  1. To create comments, change the file as follows:
     
    // Project Name: Exercise
    // Purpose:      Used to process cleaning orders for customers
    
    using System;
    
    // Orders and business-related operations will be performed here
    namespace GeorgetownCleaners
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			Console.WriteLine("Georgetown Cleaning Services");
    		}
    	}
    }
  2. Execute the application to test it
  3. Close the window and return to Visual C#
 

Command Line Options

To see the name of the executable created for the above project, you can open Windows Explorer or My Computer, display the contents of the Exercise1 folder, followed by bin, and followed by debug. You would find a program called exercise1.exe

 

By default, Microsoft Visual C# uses the name of the project to create the name of the executable of a project. In some cases, you may want to use a different name. To specify this information, you can open the properties of the project. To do this, you can click Project -> ProjectName Properties... from the main menu. Alternatively, in the Solution Explorer, you can right-click the name of the project and click Properties. Once in the properties, change the name of the Assembly Name.

 

Practical LearningPractical Learning: Specifying the Name of the Executable

  1. Click anywhere in the source file to make sure the project is selected. On the main menu, click Project -> Exercise1 Properties...
  2. To specify a custom name, delete the contents of Assembly Name and type
    Georgetown Cleaning Services
     
  3. Click OK
  4. Execute the application
  5. Open Windows Explorer or My Computer and display the contents of the Exercise1\bin\debug folder to notice an executable named Georgetown Cleaning Services
  6. Return to Visual C#

Unsafe Code

When C# was invented, one of its biggest goals was to avoid some of the difficulties of C/C++. Among them was the use of pointers for people who couldn't stand them or those who don't like or can't stand their intricacies. C/C++ uses pointers to refer to the area in memory where a value is located. C# highly avoids pointers and takes over memory management as opposed to letting the programmer take care of that aspect of an application. You can still use pointers in C# in extreme cases you judge them necessary.

Because the C# compiler is in charge of managing the memory used by the values of an application, pointers are said to be unsafe. If you want to use a pointer in your application, you must precede the name of every method that uses unsafe code with the unsafe keyword. To compile the application, you must indicate that you are using unsafe code. To do that, use the /unsafe modifier.

 
 

Copyright © 2005-2012 FunctionX Next