C# CSharp C#.Net Tutorial

C#.Net Tutorial #3

Welcome to the third C# tutorial. You'll be please to know that we'll getting into something a little meatier in this tutorial including displaying some windows (oh, alright, message boxes). Something I haven't mentioned is indenting of the code with tabs. By indenting blocks of code, it makes it much easier to read and to make sense of all the curly brackets which have to all be present otherwise it results in a compiler error. Right, now we get into making decisions using the if statement. It looks soemthing like this:-

using System;

class hello
{
	public static void Main()
	{
		int i=1;
		int j=2;

		if(i==j)
		{
			Console.WriteLine("First part of statement 1 is executed");
		}
		else
		{
			Console.WriteLine("Second part of statement 1 is executed");
		}			

		if(j>i)
		{
			Console.WriteLine("First part of statement 2 is executed");
		}
		else
		{
			Console.WriteLine("Second part of statement 2 is executed");
		}			

	}
}

The if statements breaks down into the following set of statements:-

if something
do something
otherwise
do something else

which in C# terms is:-

if(something)
{
do something
}
else
{
do something else
}

So in the top of the program we assign variables as before. Then there is a block of code like this:-

		if(i==j)
		{
			Console.WriteLine("First part of statement 1 is executed");
		}
		else
		{
			Console.WriteLine("Second part of statement 1 is executed");
		}			

The first section is asking if variable i is equal to (double equals signs) j then the first statement is executed and the else part is ignored. If i is not equal to j then the else comes into play and the second statement is executed and displays a different message. The if statements are always enclosed in brackets and there is no semicolon because there is an opening bracket. Purists may wonder why I always use the curly brackets when actually you can do without them. I personally always write it this way because it is clearer and gets me in to good habits.

The second block of if code has a different comparison in the brackets as follows:-

if(j>i);

This is saying if j is greater than i (the sharp right bracket) then satement 1 is executed otherwise statement 2. Other comparison operators are:-

< less than
<= less than or equal to
>= greater than or equal to

Have a play around with the code. Try these comparisons and switch them around and see if they react the way you expect.

Now we come around to displaying some message boxes. If you are familiar with Visual Basic 6.0 then you will have come across them. They were called msgbox in VB6 but this has been changed to MessageBox.show. Here's some code to display one:-

using System;
using System.Windows.Forms;

class hello
{
	public static void Main()
	{
		MessageBox.Show("Hello");

		MessageBox.Show("Hello", "My Hello Application", 
			MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);

		if(MessageBox.Show("Yes or No?", "My Hello Application", 
			MessageBoxButtons.YesNo, MessageBoxIcon.Question,
			MessageBoxDefaultButton.Button1)
			== DialogResult.Yes)
		{
			Console.WriteLine("You selected Yes button");
		}
		else
		{
			Console.WriteLine("You selected No button");
		}

	}
}

This starts with another using statement which includes the windows forms library which we need even though we are still programming in a console window. The first block of code just displays a messagebox with its default look. The second block displays it with a title as well as an instruction to the user and displays 2 buttons (OK and Cancel) and an exclamation mark icon. There are other icons you can display (question, asterisk etc) and other types of button layout and these will popup time and time again during the course of these tutorials. The next lot of code has the by now familiar if statement which displays a messagebox this time with Yes/No buttons and a question icon. It also sets the default button to be the first button (the second would be button2). This rather convoluted statement is also looking for the user to click on the Yes button and displays the appropriate message in the console window - if No is selected then the else statement comes into play. It may look complicated but it is just a series of staements seperated by commas and it can be as simple or as complicated as you like. It breaksdown as follows:-

Show the nessagebox with a message to the user (Yes or No?), a title of the box ("My Hello Application), Yes/No buttons, display Question icon and set the default button (the one surrounded by a black line and the one that will respond to a keypress such as SPACE or RETURN) to the first button taken from right to left. Nothing to it really. The only other thing to know about messageboxes is that they are modal (they stop the program and other messageboxes from running) and always display in the centre of the screen.

Well that was nice and easy. Now how about showing an InputBox (asks the user to input a string). Piece of cake. Ummm...ecept that C# doesn't seem to have one. What? Surely a mistake. A long search of MSDN produces the somewhat strange conclusion that it simply hasn't been coded into C#. Very odd. Now there seems to be two schools of thought as to how to deal with this amongst users on the Internet - don't bother or make your own. Not very helpful. There must be an easier way? Well there is but it requires a bit of a sideways glance at VB. Some VB commands are available in a DLL and this can be used inside a C# program. After much fiddling, here's the results of my toils:-

using System;
using Microsoft.VisualBasic;
using System.Windows.Forms;

class InpBox
{
	public static void Main()
	{
		String message, title, defaultValue;
		String Result;

		message = "Enter a name";
		title = "InputBox Demo";   
		defaultValue = "dave";  

		Result = Microsoft.VisualBasic.Interaction.InputBox(
			message, title, defaultValue, 100, 100);

		if(Result.ToLower() == "nick")
		{
			MessageBox.Show("Hello " + Result);
		}
		else
		{	
			MessageBox.Show("Incorrect name " + Result + ". Should be nick");
		}
	}
}

However, don't go rushing off trying to compile it. You need to add a reference to the DLL before we can compile it (you can't make a reference in the code itself). It is done on the command line as follows:-

csc /r:c:\windows\microsoft.net\framework\v1.1.4322\Microsoft.VisualBasic.dll inpbox.cs

assuming that the path is correct (your machine might be slightly different) and that the above program has been saved in a notepad file as inpbox.cs. This bit of information took quite a while to dig out of all the MS documentation. So what is all this doing? Note the addition of a using VisualBasic statement. In main() we setup some variables (they are shown here seperated by cmmas which is another way of doing it providing they are all of the same type (String in this case). Then they are all assigned a value. Not only does the InputBox have a title and a user message but has a default value that is put into the text box which the user either accepts or overtypes. It can also be place on the screen usibng the 100,100. All of these MUST be included in the call to the InputBox routine otherwise a compiler error is generated. Then there is the result (which is changed to lower case) and the rest you should be able to work out for yourself. Change your batch file with the above path and the /r: which offers a reference to the compiler. And thats it! Phew!

I think that wraps it up for this tutorial. If you have any problems or queries then please email me at the address below. On to loops and things next time. See you there...

Back to C# Tutor

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