Archive for the ‘C Sharp (c#)’ Category

Events – fire that event

Friday, February 19th, 2010

An event will be fired when something has happened and then you can link to that event and do something else if you wanted to. To start of with you have to link a event with a delegate function which will be the event handler.

To setup a delegate you can have the object and also any event arguments ( you can add in more if you want to, but these are the basics to include)

	// setup a delegate for the event to fire with.
	public delegate void ChangedEventHandler(object sender, EventArgs e);

here is the class that will actual fire the event, to start with I link the “event” to a virtual method as such called Changed (with the delegate from above ChangedEventHander).

	// this is the MyEvent class that will create the event fired.
	public class MyEvent 
	{
		private int x;
 
		// the event for this internal class
		public event ChangedEventHandler Changed;

here is the event firing function, this will call the Changed “virtual” method as such when ever you call this function.

		protected virtual void ThisHasChanged(EventArgs e)
		{
			// try and call the delegate ChangedEventHandler
			// make sure that there is something to call for the event to fire.
			if (Changed != null)
				Changed(this, e);
		}

and here is the get/set for the internal X variable and in the set I call the ThisHasChanged function above.

		// call the ThisHasChanged event when you set the internal value of X.
		public int xValue
		{
			get { return x;}
			set { x = value;ThisHasChanged(EventArgs.Empty); }
		}
	}

So that is the event firing, but you will need to have a listener that will listen to any events and call something that will deal with the fired event, so here is the listener class.

So the listener, is just like any other class, but you will need to have a internal reference to the class above so that you can link to the event fired, so here is the MyEvent internal class for the listener.

	// the listener for the event firing
	class EventListener
	{
		// MyEvent class
		private MyEvent ThisIsMyEvent;

and then the constructor for the EventListener, you pass in the MyEvent class that you want to “link” (the one that you will create within the running part of the program). and from within the MyEvent, there was a “virtual” method as such called “Changed”, well now we can create a link so that when that event “Changed” has been called from within the MyEvent Class I can link to a function within this class EventListener with using a new delegate ChangedEventHandler and the ValueHadChanged is within the EventListener class.

		// the class constructor and you need to pass the MyEvent class to link to the listener.
		public EventListener(MyEvent SetUpTheEventLink)
		{
			// Create a link to the MyEvent class passed in to the internal MyEvent Class
			ThisIsMyEvent = SetUpTheEventLink;
			// this is the link to the listern function.
			ThisIsMyEvent.Changed += new ChangedEventHandler(ValueHadChange);
		}

here is the ValueHadChange, same setup as the delegate parameters since we are basically passing event details between them both and can pass in more details is you want to, but you really only want to have the object (the MyEvent class) and any event arguments e.g. errors etc. at present it just says , “Oh yeah.. I have altered”.

		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
		}

since there was a Changed link attached to the above function, to clean up you can detach the link with using something similar to the constructor of this class, but instead of using += (to add) you just need to subtract from the Change virtual method -=

		// detach the listener function from the event MyEvent 
		public void Detach()
		{
			// take the event linked from the MyEvent class.
			ThisIsMyEvent.Changed -= new ChangedEventHandler(ValueHadChange);
			ThisIsMyEvent = null;
		}
	}

Here is the full code

using System;
 
// when alter a number in the internal part of the class.
namespace codingfriendsEvents
{
	// setup a delegate for the event to fire with.
	public delegate void ChangedEventHandler(object sender, EventArgs e);
 
	// this is the MyEvent class that will create the event fired.
	public class MyEvent 
	{
		// the event for this internal class
		public event ChangedEventHandler Changed;
 
		private int x;
 
		protected virtual void ThisHasChanged(EventArgs e)
		{
			// try and call the delegate ChangedEventHandler
			// make sure that there is something to call for the event to fire.
			if (Changed != null)
				Changed(this, e);
		}
 
		// call the ThisHasChanged event when you set the internal value of X.
		public int xValue
		{
			get { return x;}
			set { x = value;ThisHasChanged(EventArgs.Empty); }
		}
	}
 
	// the listener for the event firing
	class EventListener
	{
		// MyEvent class
		private MyEvent ThisIsMyEvent;
 
		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
		}
 
		// the class constructor and you need to pass the MyEvent class to link to the listener.
		public EventListener(MyEvent SetUpTheEventLink)
		{
			// Create a link to the MyEvent class passed in to the internal MyEvent Class
			ThisIsMyEvent = SetUpTheEventLink;
			// this is the link to the listern function.
			ThisIsMyEvent.Changed += new ChangedEventHandler(ValueHadChange);
		}
 
		// detach the listener function from the event MyEvent 
		public void Detach()
		{
			// take the event linked from the MyEvent class.
			ThisIsMyEvent.Changed -= new ChangedEventHandler(ValueHadChange);
			ThisIsMyEvent = null;
		}
	}
 
	class TestMyEvent
	{
		public static void Main()
		{
			// create a new MyEvent class
			MyEvent MyEventToCheck = new MyEvent();
 
			// link in with the EventLister , passing in the class of MyEvent
			EventListener TheListener = new EventListener(MyEventToCheck);
 
			// should fire of a event !! because I am changing the internal x value.
			MyEventToCheck.xValue = 10;
 
			// will not fire a event because I have not changed it.
			Console.WriteLine("X = " + MyEventToCheck.xValue);
 
			// will fire of another event.
			MyEventToCheck.xValue = 5;
 
			TheListener.Detach();
		}
	}
}

and here would be the output

Oh yeah.. I have been altered
X = 10
Oh yeah.. I have been altered

If you want to gain access to the object sender within the EventListener class to the function that was listening to the event fired, if you alter it as below, but also since because the MyEvent was also linked within the constructor you also have that link as well.

		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
			Console.WriteLine("New value of X = " + ((MyEvent)sender).xValue);
			Console.WriteLine("Internal MyEvent class x = " + ThisIsMyEvent.xValue);
		}

then you can gain access to the MyEvent from within the object sender and the output would be

Oh yeah.. I have been altered
New value of X = 10
Internal MyEvent class x = 10
X = 10
Oh yeah.. I have been altered
New value of X = 5
Internal MyEvent class x = 5

Equals why ? and why not ==

Tuesday, February 16th, 2010

In Object oriented programming languages, there is a nice keyword that is “new” what this does is create a new instance of a object and run the objects constructor method and setup up the internal variables, for example.

class classA 
{
	private int x;
 	public	classA() { x= 0;}
	public	classA(int value) { x = value;}
}
...
classA a = new classA();

this will create a new instance of A with the constructor (same name as the class) setting x equal to 0. What is happening is that the variable “a” is pointing to a memory location of the newly created object on the memory heap for example.

Local variables

Object Memory location / value
a 0×0102

which the 0×0102 memory location is pointing to a newly constructed classA space

Memory location Object values
0×0102 classA – a instance over head (garage collection etc)
0×0104 x value 0

There is over head details associated with the classA (a instance) for the garage collection/polymorphism for example. So the actual “a” variable is just pointing to this place in memory, if you created a new classA instance then another place in memory will be created, for example lets create classA a2 as

classA a2 = new classA();

and now a example of the memory locations / values would be similar to

Local variables

Object Memory location / value
a 0×0102
a2 0×0108

with the memory heap as such.

Memory location Object values
0×0102 classA – a instance over head (garage collection etc)
0×0104 x value 0
0×0108 classA – a2 instance over head (garage collection etc)
0×010a x value 0

so you would have thought that if you did,

if (a == a2)

then they would be equal, since both have a value of 0 ? well this is not the case, since the == is just comparing the value within the variable and thus the a = 0×0102 and a2 = 0×0108 which are not equal. To compare two different instances of a class you need to override the Equals function within the class (all classes are derived from object class)

So the code would be

		// override the inhertant object object Equals function
		public override bool Equals(object obj)
		{
			// cast the obj into a classA and then compare the x values
			if (x == ((classA)obj).x)
				return true;
			else
				return false;
		}

and now you can compare the two classA instances with

if (a.Equals(a2))

since the Equals function is actually comparing the values within the class instance and not the a/a2 variable values (which point to memory locations).

Here is the full code

using System;
 
namespace equaltest
{
	class classA 
	{
		private int x;
	 	public	classA() { x= 0;}
		public	classA(int value) { x = value;}
 
		public int xValue {
			get { return x;}
			set { x = value;}
		}
 
		// override the inhertant object object Equals function
		public override bool Equals(object obj)
		{
			// cast the obj into a classA and then compare the x values
			if (x == ((classA)obj).x)
				return true;
			else
				return false;
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			classA a = new classA();
			a.xValue = 10;
			Console.WriteLine("A x value = " + a.xValue);
 
			classA a2 = new classA();
			a2.xValue = 10;
			Console.WriteLine("A2 x value = " +a2.xValue);
			//so they are the same in x values, but are they the same !! ==
 
			if (a == a2)
				Console.WriteLine("a does equal a2");
			else
				Console.WriteLine("a does not equal a2");
 
			// of course they are NOT the same value, because the equals is comparing there actual object values
			// and not there x value inside them, and with the "new" keyword they are both pointing to different 
			// places on the heap of storage, thus they are NOT the same..
			// a may equal heap storage = 0x1010
			// a2 may equal heap storage= 0x1020
			// both have the same x value but different memory location values.
 
			// but implementing a Eqauls comparsion function you can compare the two variables internals 
			// as you see fit.
			if (a.Equals(a2))
				Console.WriteLine("a does equal a2");
			else
				Console.WriteLine("a does not equal a2");
 
		}
	}
}

and the output would be

A x value = 10
A2 x value = 10
a does not equal a2
a does equal a2

since I am overriding the Equals from the base object class, the compiler may warn that I am not overriding the GetHaseCode(), but that is k for this example.

Example of the compiler warning message

Description=`equaltest.classA' overrides Object.Equals(object) but does not override Object.GetHashCode()(CS0659)]

Delegates – csharp

Monday, January 18th, 2010

A delegate, is how to reference a method, something like function pointer in c++. One of the main questions of why is there a delegate/function pointer, it is because it gives the developer/user maximum amount of flexibility, lets say that you have a list of functions that you want to call if someone passes you there name and these functions could be, join together with surname, add in there ID code to there class and some other functions at the users decision like what is there car registration etc. well a delegate/function pointer can allow for different methods be called without having a set process at compile time. You could take path a , b or even c. It is harder to test with sometimes, but as long as the test process has a line to follow as well then things are good.

The delegate syntax is like other methods apart from the operative word delegate is just before the return type and there is no code within the body, it is more of a skeleton of a method/function and return type.

Here is the basic delegate syntax.

public delegate int Compare(object object1, object object2);

I have included this within the code below, what the code does is to create 5 names, and there is a sort to order the names with the returned value from the compared method/function (bubble sort). But the Compare function could be changed to order A-Z, Z-A etc.. since you can have different Compare’s methods coded but just alter one line of code to call the new method/function.

Compare compare = new Compare(SimpleDelegateName.CompareNames);

that one.

Anyway, hope that the code/comments make sense and also help to give reasons for the delegate and how it is useful.

using System;
 
namespace SimpleDelegate
{
	// setup a basic delegate to compare two objects.
	// return values = 0 (same), 1 (object1 > object2), -1 (object1 < object2)
	public delegate int Compare(object object1, object object2);
 
	class SimpleDelegateName 
	{
		// has to be a static otherwise when you try to create a instance of Compare (the delegate)
		// it will not have anywhere to point to, since static means create method even if not creating
		// the object
		public static int CompareNames(object obj1, object obj2)
		{
			// conver the objects into strings
			string name1 = obj1.ToString();
			string name2 = obj2.ToString();
 
			if (String.Compare(name2,name1) > 0)
			{
				return 1;
			} else if (String.Compare(name2, name1) < 0)
			{
				return -1;
			} else 
			{
				return 0;
			}
		}
 
		public SimpleDelegateName() 
		{
			name = "";
		}
 
		public SimpleDelegateName(String pName)
		{
			name = pName;
		}
 
		public String returnName()
		{
			return name;
		}
 
		private String name;
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			// create 5 names
			SimpleDelegateName[] names = new SimpleDelegateName[5];
			names[0] = new SimpleDelegateName("Ian");
			names[1] = new SimpleDelegateName("John");
			names[2] = new SimpleDelegateName("Alice");
			names[3] = new SimpleDelegateName("Tom");
			names[4] = new SimpleDelegateName("Katie");
			// they are no pictular order.
 
			// the delegate instance varibale
			// create a new compare object with the CompareNames method within the SimpleDeleteName class
			Compare compare = new Compare(SimpleDelegateName.CompareNames);
 
			// the basic bubble sort, moves 1 word at a time up/down the array
			object temp;
			for (int i = 0; i < names.Length; i++)
			{
				for (int j = 0; j < names.Length; j++)
				{
					Console.WriteLine("DEBUG : i = " + i + " j = " + j 
					                   + " name 1 =  " + names[i].returnName() + " name 2 = " + names[j].returnName() 
					                  	+ " compare " + compare(names[i].returnName(), names[j].returnName()));
					// if the names[i] is greater than names[j] then swap the names around.
					if (compare(names[i].returnName(), names[j].returnName()) >0)
					{
						Console.WriteLine("DEBUG : " +names[i].returnName() + "   " + names[j].returnName());
						temp = names[i];
						names[i] = names[j];
						names[j] = (SimpleDelegateName)temp;
						// swapped..
						Console.WriteLine("DEBUG : " +names[i].returnName() + "   " + names[j].returnName() + " SWAPPED");
					}
				}
			}
 
			// print out the names in alphabetical order
			foreach (SimpleDelegateName n in names)
			{
				Console.WriteLine("Name : " + n.returnName());
			}
		}
	}
}
DEBUG : i = 0 j = 0 name 1 =  Ian name 2 = Ian compare 0
DEBUG : i = 0 j = 1 name 1 =  Ian name 2 = John compare 1
DEBUG : Ian   John
DEBUG : John   Ian SWAPPED
DEBUG : i = 0 j = 2 name 1 =  John name 2 = Alice compare -1
DEBUG : i = 0 j = 3 name 1 =  John name 2 = Tom compare 1
DEBUG : John   Tom
DEBUG : Tom   John SWAPPED
DEBUG : i = 0 j = 4 name 1 =  Tom name 2 = Katie compare -1
DEBUG : i = 1 j = 0 name 1 =  Ian name 2 = Tom compare 1
DEBUG : Ian   Tom
DEBUG : Tom   Ian SWAPPED
DEBUG : i = 1 j = 1 name 1 =  Tom name 2 = Tom compare 0
DEBUG : i = 1 j = 2 name 1 =  Tom name 2 = Alice compare -1
DEBUG : i = 1 j = 3 name 1 =  Tom name 2 = John compare -1
DEBUG : i = 1 j = 4 name 1 =  Tom name 2 = Katie compare -1
DEBUG : i = 2 j = 0 name 1 =  Alice name 2 = Ian compare 1
DEBUG : Alice   Ian
DEBUG : Ian   Alice SWAPPED
DEBUG : i = 2 j = 1 name 1 =  Ian name 2 = Tom compare 1
DEBUG : Ian   Tom
DEBUG : Tom   Ian SWAPPED
DEBUG : i = 2 j = 2 name 1 =  Tom name 2 = Tom compare 0
DEBUG : i = 2 j = 3 name 1 =  Tom name 2 = John compare -1
DEBUG : i = 2 j = 4 name 1 =  Tom name 2 = Katie compare -1
DEBUG : i = 3 j = 0 name 1 =  John name 2 = Alice compare -1
DEBUG : i = 3 j = 1 name 1 =  John name 2 = Ian compare -1
DEBUG : i = 3 j = 2 name 1 =  John name 2 = Tom compare 1
DEBUG : John   Tom
DEBUG : Tom   John SWAPPED
DEBUG : i = 3 j = 3 name 1 =  Tom name 2 = Tom compare 0
DEBUG : i = 3 j = 4 name 1 =  Tom name 2 = Katie compare -1
DEBUG : i = 4 j = 0 name 1 =  Katie name 2 = Alice compare -1
DEBUG : i = 4 j = 1 name 1 =  Katie name 2 = Ian compare -1
DEBUG : i = 4 j = 2 name 1 =  Katie name 2 = John compare -1
DEBUG : i = 4 j = 3 name 1 =  Katie name 2 = Tom compare 1
DEBUG : Katie   Tom
DEBUG : Tom   Katie SWAPPED
DEBUG : i = 4 j = 4 name 1 =  Tom name 2 = Tom compare 0
Name : Alice
Name : Ian
Name : John
Name : Katie
Name : Tom

Overrideing polymorphism – c#

Friday, January 15th, 2010

Overrideing is also similar to overloading (sometimes it can be called the same thing since you are overloading/polymorphism functions and classes).

Polymorphism is when you implement functions that are defined in the base class, overriding is when you over ride a base class function.

But with Overrideing classes in c# you can override functions from the base class that are declared as virtual. Virtual means that they are capable of being overridden in a inherited class, so that incase someone tries to call a method of a same name in a subclass then the base class is still called e.g. sometimes better using code and output to show more than what words can say.

Here is not using the virtual keyword in the base class, so that when you try to call the subclasses same method it still goes to the base class.

using System;
 
namespace polymorphism
{
	class Shape {
		public void printName()
		{
			Console.WriteLine("Shape base class");
		}
	}
 
	class Circle : Shape {
		public new void printName()
		{
			Console.WriteLine("Circle class");
		}
	}
 
	class Rectangle : Shape {
		public new void printName()
		{
			Console.WriteLine("Rectangle class");
		}
	}
 
	class Line : Shape {
		public new void printName()
		{
			Console.WriteLine("Line class");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Shape[] shapesArray = new Shape[4];
			shapesArray[0] = new Shape();
			shapesArray[1] = new Circle();
			shapesArray[2] = new Rectangle();
			shapesArray[3] = new Line();
 
			foreach (Shape shape in shapesArray)
			{
				shape.printName();
			}
		}
	}
}

output would

Shape base class
Shape base class
Shape base class
Shape base class

but with the

virtual -  override

keywords.

The code

using System;
 
namespace polymorphism
{ 
	class Shape {
		public virtual void printName()
		{
			Console.WriteLine("Shape base class");
		}
	}
 
	class Circle : Shape {
		public override void printName()
		{
			Console.WriteLine("Circle class");
		}
	}
 
	class Rectangle : Shape {
		public override  void printName()
		{
			Console.WriteLine("Rectangle class");
		}
	}
 
	class Line : Shape {
		public override  void printName()
		{
			Console.WriteLine("Line class");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Shape[] shapesArray = new Shape[4];
			shapesArray[0] = new Shape();
			shapesArray[1] = new Circle();
			shapesArray[2] = new Rectangle();
			shapesArray[3] = new Line();
 
			foreach (Shape shape in shapesArray)
			{
				shape.printName();
			}
		}
	}
}

As expected the printName() function was called from the subclasses, because of the virtual keyword.

Shape base class
Circle class
Rectangle class
Line class

Overloading methods – c#

Thursday, January 14th, 2010

Overloading a method in a class is making a method name be able to take different parameters and return values. A good example would be if you had a method that was adding a passed value to a internal private variable, but wanted to be able to do different processes if the value is a integer /double / floating point number. To overload a method as above the code would be similar to this

public void addNumber(int intValue)
{
....
}
 
public void addNumber(double doubleValue)
{
...
}

Here is a basic overloading method, to just print out to the console a message.

using System;
 
namespace inheritance
{
 
	class firstClass
	{
		public void printClassName()
		{
			Console.WriteLine("FirstClass");
		}
 
		// overloading the method printClassName
		public void printClassName(String additionalMessage)
		{
			Console.WriteLine("FirstClass  : " + additionalMessage);
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			firstClass first = new firstClass();
			first.printClassName();
			// call the overloaded function to pass in a message to print out.
			first.printClassName("overloaded");
		}
	}
}

output would be

FirstClass
FirstClass  : overloaded

Inheritance and over riding methods – c#

Thursday, January 14th, 2010

Inheritance allows one class to be expanded on in further classes. The protected method/variables in the base class is accessible to the inherited classes, but the private method/variables are not.

Here is a very basic inheritance

using System;
 
namespace inheritance
{
 
	class firstClass
	{
		public void printFirstOut()
		{
			Console.WriteLine("Hi from the first class");
		}
 
	}
 
	class secondClass : firstClass
	{
		public void printSecondOut()
		{
			Console.WriteLine("Hi from second class");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			secondClass sec = new secondClass();
			// can still call the first class method
			sec.printFirstOut();
 
			// and also the second class method of course
			sec.printSecondOut();
 
			firstClass first = new firstClass();
			// can print out the first class method
			first.printFirstOut();
 
			// but first does not have knowledge of the printSecondOut() method
			// because it is not linked. Error below.
//			first.printSecondOut();
			// Description=Type `inheritance.firstClass' does not contain a definition for `printSecondOut' 
			// and no extension method `printSecondOut' of type `inheritance.firstClass' 
			// could be found (are you missing a using directive or an assembly reference?)(CS1061)]
		}
	}
}

output would be

Hi from the first class
Hi from second class
Hi from the first class

Over riding of methods from the base class can happen to make a version 2 of a class as such.

The printClassName() method below is override’d in the secondClass and it requires to have the word ‘new’ because then that tells the compiler to over ride the method in the secondclass, it may come back with a warning in the compiling of this project to say that there is a same method name in the inherited class.

using System;
 
namespace inheritance
{
 
	class firstClass
	{
		public void printClassName()
		{
			Console.WriteLine("FirstClass");
		}
	}
 
	class secondClass : firstClass
	{
		new public void printClassName()
		{
			Console.WriteLine("SecondClass");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			firstClass first = new firstClass();
			first.printClassName();
 
			secondClass sec = new secondClass();
			sec.printClassName();
		}
	}
}

output would be

FirstClass
SecondClass

Wordseach c# – WordToSearchGrid

Thursday, January 14th, 2010

The WordToSearchGrid is basically the last part of the beginning part of the wordsearch project. It brings together the grid class (which it in inheriting from) and the word class.

The direction of the words are like a compass directions, north, south, east and west and the north east, south east, north west and south west. Their are 8 directions in total that a word can take.

The getWords function gets the words to search for.

For testing, I have overloaded the createRowGrid method in the grid class. So just need to comment out the method in the class below.

I have already done a version of this code in PHP and more of a detailed information about the createSearchGrid method is on this PHP WordToSearchGrid webpage. But hopefully the comments are good enough in the code below to explain why and what is happening.

To compile up the whole thing, the Word and Grid classes will need to be included in the source code.

using System;
using System.Xml;
using System.Collections;
 
namespace wordsearchcsharp
{
	/*
	 * WordToSearchGrid extends / Inheritance from the base Grid class
	 * so that the basics of the grid class can be used e.g. creation of a random grid etc.
	 */
 
	class WordToSearchGrid : Grid
	{
		// I like to use privates instead of protected variables so that each class
		// has access to there private variables
		private String[] _words;
 
		// the constructor to call the base constructor would use 
		public WordToSearchGrid() : base() {}
		public WordToSearchGrid(int size) : base (size) {}
 
                // create a empty grid - override ('new') the base class method.
		public override char[] createGridRow()
		{
			char[] retArray = new char[returnSize()];
			for (int i =0; i < returnSize(); i++)
			{
				retArray[i] = ' ';
			}
			return retArray;
		}
 
		// get the words from the words class into this class.
		public void getWords(String[] wordsArray)
		{
			this._words = wordsArray;
		}
 
	    // print out the words to search for that have been inserted into the grid
		public void printTheWordsToSearch()
		{
			Console.WriteLine("Words to search for : ");
			foreach (string st in this._words)
			{
				Console.WriteLine(st);
			}
		}
 
		// insertIntoGrid at point position X (pX) and Y (pY) with the word and direction
		public void insertIntoGrid(int pX, int pY, String word, int direction)
		{
			int wordLen = word.Length;
 
			// move the starting point of the word to the correct place within the grid
			// the default is north and west, so will need to correct for south and east directions.
			if (direction >= 4 && direction <=6) pY-=(wordLen-1);
			if (direction >= 2 && direction <=4) pX-=(wordLen-1);
 
			// 1 = north , 2 = north east, 3 = east, 4 = south east, 5 = south, 6 = south west, 7 = west, 8= north west
			// process each letter of the word and move the position to insert in the correct direction
			for (int i =0; i < wordLen; i++)
			{
				insertCharIntoGrid(pX, pY, word[i]);
				switch (direction)
				{
			      case 1 : pY--; break;
			      case 2 : pY--; pX++; break;
			      case 3 : pX++; break;
			      case 4 : pY++; pX++; break;
			      case 5 : pY++; break;
			      case 6 : pY++; pX--; break;
			      case 7 : pX--; break;
			      case 8 : pY--; pX--; break;
			      default : break;
				}
			}
		}
 
	    // createSearchGrid, will insert the words onto a blank grid (for testing).
	    // in random places and directions.
		public void createSearchGrid()
		{
			Random rand = new Random((int)DateTime.Now.Ticks);
			int wordLen, direction, pointX, pointY, space, spaceY, spaceX;
			// loop thought the words to insert
			for (int i =0; i < _words.Length; i++)
			{
				wordLen = _words[i].Length;
				// if the word is larger than the size of the grid, it cannot be inserted.
 
			    // NOTE : at present there is no intersection (crossing search words) shall do in the next version
				if (wordLen < _size)
				{
			        //need to pick a direction and also a point on the grid.
			        // also need to try and place the word onto the grid x amount of times else break out.
					direction = rand.Next(1, _size);
					pointX = rand.Next(1, _size);
					pointY = rand.Next(1,_size);
 
				    // the remainder of the subtracting the points from the size of grid will basically say how much space is required
					space = _size - wordLen;
 
				    // check against the direction and the size of the word against where it is on the poistion in the grid
				    // 1 = north , 2 = north east, 3 = east, 4 = south east, 5 = south, 6 = south west, 7 = west, 8= north west
				    // from the points point of view.
					spaceY = _size - pointY;
					spaceX = _size - pointX;
 
				    // if the direction is not east or west, and there is not enought space, move the insertion pointY difference
					// north and south
					if (!((direction == 7) || (direction == 3)))
					{
						if (spaceY > space)
							pointY+= (spaceY - space);
					}
 
			        // if the direction is not north or south and there is not enought space, move the insertion pointX difference
			        // east and west.
					if (!((direction == 1) || (direction == 5)))
					{
						if (spaceX > space)
							pointX+= (spaceX - space);
					}
					this.insertIntoGrid(pointX, pointY, _words[i], direction);
				}
				else
				{
					Console.WriteLine("Word : " + _words[i] + " is too long for the grid of size " + _size);
				}
			}
		}
 
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Word word = new Word("words.xml",3);
			WordToSearchGrid gridWithWords = new WordToSearchGrid();
 
			// place the words into the WordToSearchGrid 
			gridWithWords.getWords(word.returnWords());
			// create a search grid with the words passed above.
			gridWithWords.createSearchGrid();
			// print out the grid		
			gridWithWords.printOutGrid();
			// print out the words to search
			gridWithWords.printTheWordsToSearch();
			// of course could have used the Word class
			// but since this is the WordToSearchGrid, so just placed one method in there as well.
			word.printOutWords();
		}
	}
}

and a example output would be with the testing blank grid created.

The Grid
0 ..0 =  1 =  2 =  3 =  4 =  5 =  6 =  7 =  8 =  9 =  10 =  
1 ..0 =  1 =  2 =  3 =  4 =  5 =  6 =  7 =  8 = o9 =  10 =  
2 ..0 =  1 =  2 =  3 =  4 =  5 =  6 =  7 =  8 =  9 = l10 =  
3 ..0 =  1 =  2 =  3 =  4 =  5 =  6 =  7 =  8 =  9 =  10 = d
4 ..0 =  1 =  2 =  3 =  4 =  5 =  6 =  7 =  8 =  9 =  10 =  
5 ..0 =  1 =  2 =  3 =  4 = s5 =  6 =  7 =  8 =  9 =  10 =  
6 ..0 =  1 =  2 =  3 =  4 =  5 = o6 =  7 =  8 =  9 =  10 =  
7 ..0 =  1 =  2 =  3 =  4 =  5 =  6 = l7 =  8 =  9 =  10 = w 
8 ..0 =  1 =  2 =  3 =  4 =  5 =  6 =  7 = e8 =  9 =  10 = a 
9 ..0 =  1 =  2 =  3 =  4 =  5 =  6 =  7 =  8 =  9 =  10 = s
10 ..0 =  1 =  2 =  3 =  4 =  5 =  6 =  7 =  8 =  9 =  10 =  
Words to search for : 
old
was
sole
Words : (  0 = old  1 = was  2 = sole)

and output without the testing blank grid

The Grid
0 ..0 = u1 = r2 = s3 = f4 = x5 = b6 = a7 = o8 = m9 = j10 = m
1 ..0 = s1 = s2 = o3 = l4 = e5 = k6 = h7 = g8 = v9 = e10 = h
2 ..0 = a1 = y2 = l3 = a4 = q5 = a6 = q7 = i8 = x9 = s10 = i
3 ..0 = t1 = j2 = q3 = x4 = r5 = b6 = s7 = m8 = g9 = f10 = d
4 ..0 = m1 = t2 = v3 = u4 = r5 = c6 = t7 = q8 = o9 = s10 = w
5 ..0 = g1 = f2 = c3 = s4 = r5 = d6 = v7 = u8 = x9 = f10 = r
6 ..0 = n1 = c2 = s3 = q4 = v5 = t6 = f7 = w8 = a9 = t10 = s
7 ..0 = h1 = m2 = y3 = o4 = v5 = u6 = h7 = b8 = i9 = h10 = n
8 ..0 = b1 = w2 = e3 = m4 = e5 = h6 = j7 = f8 = d9 = t10 = i
9 ..0 = u1 = i2 = j3 = k4 = w5 = w6 = l7 = k8 = l9 = h10 = c
10 ..0 = o1 = s2 = o3 = i4 = w5 = x6 = n7 = o8 = o9 = t10 = w
Words to search for : 
he
sole
old
Words : (  0 = he  1 = sole  2 = old)

Use the new keyword if hiding was intended(CS0108)

Thursday, January 14th, 2010

If you are using the inheritance in c# and are wanting to override (hide) the base class method but forget to use the ‘new’ keyword then you will get the warning.

Use the new keyword if hiding was intended(CS0108)

An example of this in coding syntax would be something like

class BC 
{
  public void DisplayMe()
  {
    System.Console.WriteLine("Display me from BC");
  }
}
// inherited class from BC
class NewBC : BC 
{
  public void DisplayMe()
  {
    System.Console.WriteLine("Display me from the NewBC :) yeppy");
  }
}
 
NewBC NBC = new NewBC();
NBC.DisplayMe();

and the output would be

Display me from the NewBC :) yeppy

If you note that the base class in the NBC has not been called from the NBC.DisplayMe() method e.g. “Display Me from BC”

But you will get the warning message from the compiler

Use the new keyword if hiding was intended(CS0108)

So all you do is to put the keyword ‘new’ before the overriding method e.g.

// inherited class from BC
class NewBC : BC 
{
  new public void DisplayMe()
  {
    System.Console.WriteLine("Display me from the NewBC :) yeppy");
  }
}

Wordsearch c# – Word class

Wednesday, January 13th, 2010

I am just doing a test/comparsion between the different ways of getting a similar code syntax to work in different languages for a similar project idea. The main project idea is wordsearch grid with words inserted onto the grid, I have already done a basic php version and here is the word class in php word. Below there is a full class version of whole class, but also some parts that I have expanded to try and explain in more detail.

This code will return a String array from a ArrayList type. The ToArray changes the ArrayList to type of string then the “as string[]” returns the list of string as a string array.

			return (arrayL.ToArray(typeof(string)) as string[]);

Here is the word class in c#, I have added allot of code comments to give details of what is happening.

using System;
using System.Xml;
using System.Collections;
 
namespace wordsearchcsharp
{
	class Word 
	{
		private String[] _words;
 
	 	public  Word() : this("words.xml", 5) {}
 
		public Word(string wordsOrFilename, int maxSearchNum)
		{
			this._words = new String[maxSearchNum];
			// just load from a file the words to search, instead of input as well.
			String[] loadedWords = loadWords(wordsOrFilename);
 
			// create the searchable words from the loadedwords array.
			this._words = this.searchableWords(loadedWords, maxSearchNum);
		}
 
		private String[] loadWords(string filename)
		{
			XmlTextReader fileReader = new XmlTextReader(filename);
 
			ArrayList fileArray = new ArrayList();
 
			while (fileReader.Read())
			{
				// get the NodeType from the XML reader, different types
				// Element = name of element
				// Text = the actual text/word
				// End Element = end of the element name
			    switch (fileReader.NodeType) 
			    {
					// if there is a word in the file e.g. not a end/element
					  case XmlNodeType.Text: 
							fileArray.Add(fileReader.Value);
				            break;
			    }
			}
			// change the ArrayList into a String[] array using the ToArray method
			return (fileArray.ToArray(typeof(string)) as string[]);
		}
 
		// create a list of words from the words passed in and also 
		// the maximum number is the maxSearchNum.
		private String[] searchableWords(String[] words, int maxSearchNum)
		{
			ArrayList returnWords = new ArrayList();
 
			// if the maxsearch value is greater or equal to the number of words to search for 
			// just return the words string[].
			if (words.Length <= maxSearchNum)
			{
				return words;
			}
			else
			{
				// create a good seed for the random generator.
				Random randGen = new Random((int)DateTime.Now.Ticks);
				int randomNum;
				// randomly pick out words from the array
				for (int i = 0; i < maxSearchNum; i++)
				{
					// pick a random number
					randomNum = randGen.Next(0, words.Length);
					// add to the array list to return
					returnWords.Add(words[randomNum]);
					// rebuild the array with removing the random number generated.
					words = rebuildArray(words, randomNum);
				}
			}
			// convert back to the String[] 
			return (returnWords.ToArray(typeof(string)) as string[]);
		}
 
		private String[] rebuildArray(String[] rebuildSt, int numberToTakeOut)
		{
			ArrayList arrayL = new ArrayList();
			// out of range error.
			if (rebuildSt.Length < numberToTakeOut)
			{
				return rebuildSt;
			}
			else
			{
				for (int i =0; i < rebuildSt.Length; i++)
				{
					// only add in the words that are not the
					// numberToTakeOut word from the array
					if (i != numberToTakeOut)
					{
						arrayL.Add(rebuildSt[i]);
					}
				}
			}
			return (arrayL.ToArray(typeof(string)) as string[]);
		}
 
		public void printOutWords()
		{
			Console.Write("Words : (");
			for (int i = 0; i < this._words.Length; i++)
			{
				Console.Write("  " + i + " = " + this._words[i]);
			}
			Console.Write(")\n");
		}
 
		public String[] returnWords()
		{
			return this._words;
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Word word = new Word("words.xml",3);
                        word.printOutWords();
		}
	}
}

and a output would be

Words : (  0 = he  1 = old  2 = sole)

Monodevelop – system.xml error

Wednesday, January 13th, 2010

I use monodevelop to create my c# applications etc and just noticed that if you want to have more references to assemblies like System.Xml then you will have to add them via the GUI.

For example, if you get the error.

Description=The type or namespace name `Xml' does not exist in the namespace `System'. Are you missing an assembly reference?(CS0234)

then you will need to add the System.Xml assembly reference into the GUI solutions manager to compile in that assembly.

If you goto Solutions box -> References -> (Right click) Edit References. In the packages tab scroll down in the list and find the System.Xml and add it to the solution. Compile again and it will work :) .. well you may get other errors but at least this one is sorted.

If you do not have the Solutions box, goto the main monodevelop menu View -> Solution.