C# C Sharp Tutorial

C# Tutorial #6

Welcome to the sixth C# tutorial (still haven't found a better way to start these tutorials). Now we are getting to the nitty gritty and to the heart of C# with the introduction of classes. Now it has to be said that up till now I have not been a big fan of classes but they are growing on me and they are implemented quite nicely in C#. So what is the big mystery? What ARE classes? Well, I've already given you a big clue in the previous tutorial. A Class is a mixture of structures (struct) and functions in one construct. Here is what a simple class looks like with its calling program:-

using System;

public class HelloWorld
{
	public int i = 1;

	public void ShowHello()
	{
		Console.WriteLine
       			("Hello World with Classes!");
	}
}

public class TestHello
{
	// This is the usual Hello World! program with classes
	public static void Main()
	{
		HelloWorld hw = new HelloWorld();
		hw.ShowHello();
		Console.WriteLine(hw.i);
		hw.i=2;
		Console.WriteLine(hw.i);
	}
}

I think I need to explain first that the class TestHello is there just contain the Main() program otherwise it won't compile. What I have done is create my own class outside of the Main() class (and could be contained inside another file) which I can call upon from the Main() program. I can create an instance of it and call functions housed within it. I can also modify variables contained within it much like in a struct. All very clever.

Sp when should you use classes? Well, you could program in C# and NEVER use them (much hissing from the auditorium and shouts of "Heresey!") at all. But you would be missing out on a whole lot of stuff. I'm not going into classes any more deeply at this stage but there are some things you ought to know about classes.

It is my aim in these tutorials to teach you enough to be able to use databases and Windows GUI forms and you don't necessarily need all the extra stuff to do it but I may return this subject in later tutorials. Here is ah enhancement to the above program:-

using System;

public class HelloWorld
{
	public int i = 1;

	public void ShowHello()
	{
		Console.WriteLine
       			("Hello World with Classes!");
	}
}

public class ShowTime
{
	public void ShowCurrentTime()
	{
		Console.WriteLine
       			("The current time is: " + DateTime.Now);
	}
}

public class TestHello
{
	// This is the usual Hello World! program with classes
	public static void Main()
	{
		HelloWorld hw = new HelloWorld();
		hw.ShowHello();
		Console.WriteLine(hw.i);
		hw.i=2;
		Console.WriteLine(hw.i);

		ShowTime st = new ShowTime();
		st.ShowCurrentTime();
	}
}

This enables you to call a class to get the current time. I was alluding in previous tutorials to how classes can contain both data structures and functions so here is a sample:-

using System;

class clsPhone
{
	string strName;
	string strNumber;

	void AddPhone()
	{
		strName="Nick";
		strNumber="01234567890";
	}

	static void Main()
	{
		clsPhone pb = new clsPhone();
		pb.AddPhone();

		Console.WriteLine(pb.strName);
		Console.WriteLine(pb.strNumber);
	}
}

Here we have both a structure than can be accessed as if it was a structure and functions that can update them. I hope that all this will become clearer as we move further into these tutorials. So that's it with classes. I have previously alluded to the fact that structures are the building blocks for creating databases. To complete such an application, you need to be able to save the information to disk and for that you need files. You need to be able to do the following things with files:-

Here is a sample program:-

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
	// create file
        string path = @"Test.txt";
        if (!File.Exists(path)) 
        {
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine("Hello");
            }    
        }

	// add to existing file
	using (StreamWriter sw = File.AppendText(path)) 
        {
            sw.WriteLine("Welcome");
        }    

        // read file
	using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}

This isn't everything as you need to be able to update individual records within files but that is really beyond the scope of these tutorials as I'm sure you're itching to get to databases proper which does all this for you so I'll leave it at that. The above program is in three sections. The first sets the file name to the current directory and if the file doesn't exist (the ! operator means NOT) then create a text file and write a line to it. It isn't necessary to close a file in C# as the using keyword does that for you. The second section appends a line of text to an existing file and the third reads it (using SteanReader rather than StreamWriter) and writes the contents to the screen until the end of the file is reached.

That wraps up files. One other thing to aquaint you with (yes databases is next!) is error checking. This is done using try, catch, finally which has been part of C++ and Java for a while but has made it into C# (and Visual Basic.Net as well). Hres some code:-

using System;

public class ExceptionTest
{
    	public static void Main()
    	{
		try 
		{
			Console.WriteLine("Try");
			int a=0;
			int b=100/a;
		}

		catch (Exception e)
		{
			Console.WriteLine("Catch");
			Console.WriteLine(e.Message);
		}

		finally
		{
			Console.WriteLine("Finally");
		}
    	}
}

It was quite difficult to find a simple bit of code to trip an exception (error to you) but here is a divide by zero error sample. The code we want to use goes inside the try section which would usually be some kind of open command which may trip an error if a file doesn't exist for example. If an error is generated then the catch part comes into play and generates an error message. The finally bit ALWAYS runs and would normally contain the file close command so the file would be closed no matter what. We will need this in the next tutorial (which will be databases...honest). See you then...

Back to C# Tutor

Written by Nick Cheesman. Last updated: 01/06/2007
Please eMail me at:
nickjc@nickjc.co.uk