Baccou Bonneville Blogs Eclipse Blog Process Improvement Blog Java Blog Web Design Blog Miscellaneous .NET Blog

01/02/06

English (US)   Introduction to C#  -  Categories: C#, .NET, Visual Studio  -  @ 02:53:17 pm

C# logoThe goal of this note is to write the classical Hello World program in C# and also to introduce some of the characteristics of the language.

[More:]

Introduction

C# has been created by Microsoft but has been normalized by ECMA under the following number: Standard ECMA-334: C# Language Specification.

1. Hello World

This is the step to create a hello world application using Visual .NET 2005:

A file called Program.cs with the following code is automatically generated:

using System;
using System.Collections.Generic;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Now, in the main function, add the following instruction:

Console.WriteLine("Hello World!");

Run the application using the menu: Debug > Start without debugging. That's it!

2. Visual Studio keybord shortcuts

It's already time to learn some keyboard shortcuts:

3. Types and Pointers

4. Arrays

5. Enumerations

This is a sample of use of an enumeration in C#:

using System;
using System.Collections.Generic;
using System.Text;

namespace HelloWorld
{
    public enum COLORS { red, green, blue }

    class Program
    {
        static void Main(string[] args)
        {            
            Array colors = Enum.GetValues(typeof(COLORS));
            foreach (COLORS c in colors)
                Console.WriteLine(c);
        }
    }
}

6. Class, abstract class and interface

A class is composed of methods and fields.

An abstract class is a class that will never have any instance. An abstract method is the declaration of a method in an abstract class without the code of the method. An inteface is a class where every methods are abstract.

A class can be declared as:

Optionnaly, you can also specify if the class will be:

To declare an interface, just replace the keyword "class" by the keyword "interface". Note that "abstract" and "new" are not allowed for an interface.

7. Structures

Structures (struct) are particular classes that cannot inherit from another class and no class inherit from it.

8. Namespaces

A namespace is a collection of classes. In a particular namespace, the names of the classes must be unique. Namespaces are declared using the "namespace" keyword and imported with the "using" keyword.

9. Methods

A method can be:

To pass an argument by reference, use the "ref" keyword as in the following sample:

class Program
{
    static void Main(string[] args)
    {
        double a = 3;
        square(ref a);
        Console.WriteLine(a);
    }

    public static void square(ref double n)
    {
        n = Math.Pow(n, 2);
    }
}

If you want a method to return more than one value, you can use the "out" keyword like in this example:

public static bool update(int article, out int value)

.

To create a method with a variable number of parameters, you must use the "params" keyword like this:

public static int add(params int[] numbers)

.

10. Fields

Concerning fields, we will use the following keywords:

11. Properties

This example illustrates how to define a property with a get and a set method:

public class User
{
    private string name;
    public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        User u = new User();
        u.Name = "John WOO";
        Console.WriteLine(u.Name);
    }
}

Note that - by convention - we use a capital letter when the property is public and a small letter when the property is private. Same idea for methods.

12. Indexers

If your class represents an array, you can use indexers as in the following example:

public class Calls
{
    public const int Max = 10;
    private string[] callers;

    public Calls()
    {
        this.callers = new string[Max];
    }

    public string this[int i]
    {
        get { return (i < Max) ? this.callers[i] : "error"; }
        set { if (i < Max) this.callers[i] = value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Calls c = new Calls();
        c[0] = "0132362558";
        Console.WriteLine(c[0]);
        Console.WriteLine(c[90]);
    }
}

13. Delegates

A delegate is interface declaring exactly one method. It is more or less similar to C/C++ function pointers but a delegate can call several functions.

class Program
{
     public delegate void MyDelegate(int a, int b);

     public static void Add(int a, int b) { Console.WriteLine(a + b); }
     public static void Remove(int a, int b) { Console.WriteLine(a - b); }

     static void Main(string[] args)
     {             
        MyDelegate a = new MyDelegate(Add);
        MyDelegate b = new MyDelegate(Remove);
        a(15, 3);
        b(15, 3);

        Console.WriteLine("And now several functions are called...");
        MyDelegate c = a + b;
        c(15, 3);
    }
}

14. Events

This example show how to use events:

class EmergencyArgs : EventArgs
{
    public string Address;
    public EmergencyArgs(string a) { Address = a; }
}

class FireBrigade
{
    public FireBrigade(Witness w)
    {
        w.Emergency += new Witness.EmergencyWarning(CallReceived);
    }

    void CallReceived(object sender, EmergencyArgs args)
    {
        Console.WriteLine("Call received for an emergency at " + args.Address);
    }
}

class Witness
{
    public delegate void EmergencyWarning(object sender, EmergencyArgs e);
    public event EmergencyWarning Emergency;
    public void CallFireBrigade()
    {
        EmergencyArgs args = new EmergencyArgs("54 Lake Road, Dallas");
        if ( Emergency != null ) Emergency(this, args);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Witness john = new Witness();
        FireBrigade f = new FireBrigade(john);
        Console.WriteLine("Press Enter to call the firebrigade");
        Console.Read();
        john.CallFireBrigade();
    }
}

15. Exceptions

The following C# keywords are use to handle exceptions:

16. Code documentation

The C# documenter is the equivalent of Javadoc. It allows to extract documentation from the code to produce an XML documentation associated to the code (whereas Javadoc generates an HTML documentation). To insert documentation in your code, you will use /// like in this example:

/// <summary>
/// The User class represent a user of the system
/// </summary>
public class User

You can use the following predefined XML tags or any XML tag you want:

Here are the steps to generate the documentation:

References

Leave a comment

Comments:

No Comments for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))
This is a captcha-picture. It is used to prevent mass-access by robots.

Please enter the characters from the image above. (case insensitive)

Pingbacks:

No Pingbacks for this post yet...

powered by
b2evolution

Credits: blog software | web hosting | monetize