01/02/06
The 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.
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:
- Install Visual .NET 2005 on your PC
- Start Microsoft Visual Studio 2005
- Create a new project using the following menu: File > New > Project > Visual C# > Console Application. Put "HelloWorld" in the name of the project.
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:
- Shift + F6: Build
- Ctrl + F5: Run
3. Types and Pointers
- The @ character allow to write a "verbatim string" with special characters like double quote:
string path = @"C:\MyDocuments\"
- The "is" operator allows to check if an object is of a certain type:
if ( object is int ) Console.Write("object contains an int"); - When you use pointers in C#, you must mark your function using the "unsafe" keyword:
unsafe static void Main(string[] args)
and you must compile with the unsafe flag.
4. Arrays
- To initialize a table of two integers, you should write:
int[] a = { 4, 5 }; To create a two-dimension array, you should write:
int[,] myArray = new int[2,3];
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:
- public: fully accessible by other types
- internal: accessible only to types within the same assembly
- protected: accessible by a containing type and any type that inherits from this containing type
- private: is limited to a containing type only
Optionnaly, you can also specify if the class will be:
- new: used for nested classes (class defined in the body of another class)
- abstract: cannot itself be instanced
- sealed: cannot be inherited from
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:
- abstract: the body of the method is not provided
- static: for a class method
- virtual: this method can be override
- override: this method is an override
- new: hides the super-class method
- extern: defined externally using another language than C#.
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:
- static: associated to class instances:
public static int max = 10;
- readonly: the value can be set once, in the class declaration for class instances or in the constructor:
public static readonly int max = 10;
- const: for constants:
public const int max = 10;
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:
- try {}: put between the braces the instructions where you can have an exception
- catch () {}: put between the parenthesis the exception to handle and the instructions between the braces
- finally {}: put here instructions that must be performed in any cases (with or without exception)
- throw new Exception();: to throw an exeption
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:
- <summary>: overview information
- <remarks>: comments
- <exception>
- <include>
- <permission>
- <see>
- <seealso>
- <value>
Here are the steps to generate the documentation:
- Open the menu View > Solution Explorer
- Open the tab named "Build"
- For both Release and Debug configurations, check the checkbox named "XML documentation file"
- Next time you will build your application, the XML documenation will be generated in the release or the debug directory.
- To generate an HTML or CHM (MSDN-like) documenation, you should install NDoc. Note that for the moment, NDoc does not support .NET 2.0.
References
- C# tutorial by Softsteel Solutions
- C# et .NET by Gérard Leblanc, Eyrolles (book in French, not available anymore)
Comments:
No Comments for this post yet...
Leave a comment:
Pingbacks:
No Pingbacks for this post yet...
Introduction to C# -
Categories: