Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Introduction to C#

Posted by Ravi Varma Thumati on March 16, 2009

Getting started with C# Programming

What is C# Language?

 

The C# language is disarmingly simple, with only about 80 keywords and a dozen built-in datatypes, but it’s highly expressive when it comes to implementing modern programming concepts. C# includes all the support for structured, component- based, object-oriented programming that you expect of a modern language built on the shoulders of C++ and Java, and now with Version 2.0, many of the most important missing ingredients, such as generics and anonymous methods, have been added.

Hello, world

 

The best way to learn a new programming language is to write code. The first example is the classic HelloWorld program. In this program, you will display some text to the screen.

 

class HelloWorld

{

 static void Main()

 {

   System.Console.WriteLine(“Hello. My name is Inigo Montoya.”);

 }

}

 

Compiling and running this code displays the words “Hello World” at the console. Before we compile and run it, let’s first take a closer look at this simple program.

 

The “Hello World” program declares a single type: the Hello class. To define a C# type, you declare it as a class using the class keyword, give it a namein this case, Helloand then define its properties and behaviors. The property and behavior definitions of a C# class must be enclosed by open and closed braces ({}).

 

A class has both properties and behaviors. Behaviors are defined with member methods.

 

A method is a function owned by your class. In fact, member methods are sometimes called member functions. The member methods define what your class can do or how it behaves. Typically, methods are given action names, such as WriteLine() or AddNumbers(). In the case shown here, however, the class method has a special name, Main(), which doesn’t describe an action but does designate to the CLR that this is the main, or first method, for your class.

 

The CLR calls Main() when your program starts. Main() is the entry point for your program, and every C# program must have a Main( ) method

Over view of a C# program

 

Some of the basic features of a C# program

 

// (1) using simplifies references to namespaces

using System;

// (2) class declaration

Class Apparel

{

            Public double Price = 250.0;

           

            Public string FabType = “ Something”;

 

            /// <remarks> Entry point to program </remarks>

}

           

Public class myApp

{

            // (3) Main() is required in each c# program

            Static void main()

            {

                        Apparel myApparel = new Apparel ();

                        string myType = myApparel.FabType;

                        Console.WriteLine(myApparel.Price, myType);

            }

}

The code in above consists of a class MyApp that contains the program logic and a class Apparel that contains the data. The program creates an instance of Apparel and assigns it to myApparel. This object is then used to print the values of the class members FabType and Price to the console. The important features to note include the following:

1.      The using statement specifies the namespace System. Recall from Chapter 1, “Introduction to .NET and C#,” that the .NET class libraries are organized into namespaces and that the System namespace contains all of the simple data types. The using statement tells the compiler to search this namespace when resolving references, making it unnecessary to use fully qualified names. For example, you can refer to label rather than System.Web.UI.WebControls.Label.

2.      All programming logic and data must be contained within a type definition. All program logic and data must be embedded in a class, structure, enum, interface, or delegate. Unlike Visual Basic, for instance, C# has no global variable that exists outside the scope of a type. Access to types and type members is strictly controlled by access modifiers. In this example, the access modifier public permits external classes—such as MyApp—to access the two members of the Apparel class.

3.      A Main() method is required for every executable C# application. This method serves as the entry point to the application; it must always have the static modifier and the M must be capitalized. Overloaded forms of Main()define a return type and accept a parameter list as input  Return an integer value:

static int Main()
 
{
   return 0; // must return an integer value
}

Receive a list of command-line arguments as a parameter and return an integer value:

static int Main(string[] args)
 
{
   // loop through arguments
 
   foreach(string myArg in args)
 
      Console.WriteLine(myArg);
   return 0;
 
}

The parameter is a string array containing the contents of the command line used to invoke the program. For example, this command line executes the program MyApparel and passes it two parameter values:

C:\> MyApparel 5 6

General C# Programming Notes

Case Sensitivity

All variable and keywords are distinguished by case sensitivity. Replace class with Class in and the code will not compile.

Naming Conventions

The ECMA standard provides naming convention guidelines to be followed in your C# code. In addition to promoting consistency, following a strict naming policy can minimize errors related to case sensitivity that often result from undisciplined naming schemes. Table 2-1 summarizes some of the more important recommendations.

Table 2-1. C# Naming Conventions

Type

Case

Notes and Examples

Class

Pascal

·         Use noun or noun phrases.

·         Try to avoid starting with I because this is reserved for interfaces.

·         Do not use underscores.

Constant

Pascal

public const double GramToPound = 454.0 ;

Enum Type

Pascal

·         Use Pascal case for the enum value names.

·         Use singular name for enums.

public enum WarmColor { Orange, Yellow, Brown}

Event

Pascal

·         The method that handles events should have the suffix EventHandler.

·         Event argument classes should have the suffix EventArgs.

Exception

Pascal

·         Has suffix Exception.

Interface

Pascal

·         Has prefix of I.

IDisposable

Local Variable

Camel

·         Variables with public access modifier use Pascal

int myIndex.

Method

Pascal

·         Use verb or verb phrases for name.

Namespace

Pascal

·         Do not have a namespace and class with the same name.

·         Use prefixes to avoid namespaces having the same name. For example, use a company name to categorize namespaces developed by that company.

Acme.GraphicsLib

Property

Pascal

·         Use noun or noun phrase.

Parameter

Camel

·         Use meaningful names that describe the parameter’s purpose.

 

Note that the case of a name may be based on two capitalization schemes:

1.      Pascal. The first character of each word is capitalized (for example, MyClassAdder).

2.      Camel. The first character of each word, except the first, is capitalized (for example, myClassAdder).

The rule of thumb is to use Pascal capitalization everywhere except with parameters and local variables.

Commenting a C# Program

The C# compiler supports three types of embedded comments: an XML version and the two single-line (//) and multi-line (/* */) comments familiar to most programmers:

//   for a single line 
 
/*   for one or more lines
 
                     */
/// <remarks> XML comment describing a class </remarks>

An XML comment begins with three slashes (///) and usually contains XML tags that document a particular aspect of the code such as a structure, a class, or class member. The C# parser can expand the XML tags to provide additional information and export them to an external file for further processing.

The <remarks> tag—shown in Figure 2-1—is used to describe a type (class). The C# compiler recognizes eight other primary tags that are associated with a particular program element. These tags are placed directly above the lines of code they refer to.

The Dot (.) Operator

In above code, the dot operator (.) is used both to access a method (and data) in a class (in this case, the method WriteLine( )), and to restrict the class name to a specific namespace (in this case, to locate Console within the System namespace). This works well because in both cases we are “drilling down” to find the exact thing we want. The top level is the System namespace (which contains all the System objects that the FCL provides); the Console type exists within that namespace, and the WriteLine() method is a member function of the Console type.

In many cases, namespaces are divided into subspaces. For example, the System namespace contains a number of subnamespaces such as Data, Configuration, Collections, and so forth, while the Collections namespace itself is divided into multiple subnamespaces.

Namespaces can help you organize and compartmentalize your types. When you write a complex C# program, you might want to create your own namespace hierarchy, and there is no limit to how deep this hierarchy can be. The goal of namespaces is to help you divide and conquer the complexity of your object hierarchy.

The using Keyword

Rather than writing the word System before Console, you could specify that you will be using types from the System namespace by writing the directive:

using System;

at the top of the listing, as shown in Example 2-3.

Example 2-3. The using keyword
using System;
class Hello
{
    static void Main( )
    {
        //Console from the System namespace
        Console.WriteLine("Hello World");
    }
}

Notice the using System directive is placed before the Hello class definition. Visual Studio .NET 2005 defaults to including three using statements in every console application (System, System.Collections.Generic, System.Text).

Although you can designate that you are using the System namespace, you can’t designate that you are using the System.Console object.

The static keyword

The Main( ) method shown in above code has one more designation. Just before the return type declaration void (which, you will remember, indicates that the method doesn’t return a value) you’ll find the keyword static:

static void Main()

The static keyword indicates that you can invoke Main( ) without first creating an object of type Hello.

Developing Hello, World

 

There are at least two ways to enter, compile, and run the programs: use the Visual Studio .NET Integrated Development Environment (IDE), or use a text editor and a command-line compiler.

 

Although you can develop software outside Visual Studio .NET, the IDE provides enormous advantages. These include indentation support, Intelli-sense word completion, color coding, and integration with the help files. Most important, the IDE includes a powerful debugger and a wealth of other tools.

 


Developing the Program in IDE:

 

To create the “Hello World” program in the IDE, select Visual Studio .NET from your Start menu or a desktop icon, and then choose File -> New -> Project from the menu toolbar. This will invoke the New Project window.

 

Fig: Creating a C# console application in Visual Studio .NET

 

To open your application, select Visual C# in the Project Types window, and choose Console Application in the Templates window (if you use the Express Edition of Visual C#, you don’t need to perform that first step; go directly to the Console Application).

You can now enter a name for the project and select a directory in which to store your files. Click OK, and a new window will appear in which you can enter the code in.

 

Fig: The editor, opened to your new project

 

Notice that Visual Studio .NET creates a namespace based on the project name you’ve provided (HelloWorld), and adds a using directive for System, System.Collections.Generic, and System.Text because nearly every program you write will need types from those namespaces.

 

Visual Studio .NET creates a class named Program, which you are free to rename. When you rename the class, it’s a good idea to rename the file as well (Class1.cs). If you rename the file, Visual Studio will automatically rename the class for you. To reproduce Example 2-1, for instance, rename the Program.cs file (listed in the Solution Explorer window) to hello.cs and change the name of Program to HelloWorld (if you do this in the reverse order, Visual Studio will rename the class to hello).

 

Finally, Visual Studio 2005 creates a program skeleton to get you started. Then copy the following two lines into the body of Main():

 

// Use the system console object

System.Console.WriteLine(“Hello World”);

 

If you aren’t using Visual Studio .NET, open Notepad, type in the code from above, and save the file as a text file named hello.cs.

 

Compiling and Running “Hello World”

 

There are many ways to compile and run the “Hello World” program from within Visual Studio. Typically you can accomplish every task by choosing commands from the Visual Studio menu toolbar, by using buttons, and, in many cases, by using key-combination shortcuts.

For example, to compile the “Hello World” program, press Ctrl-Shift-B or choose Build Build Solution. As an alternative, you can click the Build button on the Build toolbar

 

Figure 2-3. Build toolbar

 

To run the “Hello World” program without the debugger, you can press Ctrl-F5 on your keyboard, choose Debug -> Start Without Debugging from the IDE menu toolbar, or press the Start Without Debugging button on the IDE Build toolbar. You can run the program without first explicitly building it; depending on how your options are set (Tools -> Options), the IDE will save the file, build it, and run it, possibly asking you for permission at each step.

 

Figure 2-4. Start without Debugging button

 

Use the following steps to compile and run the “Hello World” program using the C# command-line compiler that comes with the .NET Framework SDK

 

Save example as the file hello.cs.

Open a .NET command window (Start -> Programs -> Visual Studio .NET -> Visual Studio Tools -> Visual Studio Command Prompt.

 

From the command line, use this command if you are using the .NET or Shared Source CLI C# compiler:

 

csc /debug hello.cs

 

This step builds the EXE file. If the program contains errors, the compiler reports them in the command window. The /debug command-line switch inserts symbols in the code so that you can run the EXE under a debugger or see line numbers in stack traces. (You’ll get a stack trace if your program generates an error that you don’t handle.)

 

To run the program under .NET, enter:

hello

 

You should now see the venerable words “Hello World” appear in your command window.

Advertisements

2 Responses to “Introduction to C#”

  1. Very effectively written information. It will likely be helpful to anyone who usess it, including myself. Keep up the good work – for positive i will try extra posts.

  2. Your posts constantly include alot of really up to date info. Where do you come up with this? Just saying you are very inspiring. Thanks again

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: