C# – Interfaces… why?

Yep, you read right. Why on earth do we use interfaces? I’ve seen a plethora of crappy examples involving shapes, fruits, vegetables, etc. attempting to explain why we use inheritance and interfaces. Bloody useless! Why? They have no proper real-world application that we can associate with. Unless you’re a mathematician or a greengrocer, why on earth would you care about fruit or shapes?

Ok, lets start with a definition of an interface.

An interface is a contract of service within a programming language.

Ok, what on earth does THAT mean? It means when you implement an interface, you are agreeing to provide functionality that satisfies the interface contract.

So… what use is that exactly?

An interface would be a structure with no implemented methods. A (terrible) example from MSDN is:


interface IMyInterface: IBase1, IBase2
{
void MethodA();
void MethodB();
}

This defines an interface with two methods. MethodA and MethodB. It has no implementation code. It also can inherit other interfaces (IBase1, IBase2) so you can structure them. That’s more a FYI than anything because that complicates things far too much for the simple explanation I want to give out.

Interfaces can be very useful. Let’s use a real-world example that we should all be fairly familiar with. Let’s pick an ATM at a bank. (I pinched this example for a C# design book I picked up about 7 years ago. I don’t have the book to hand or recall the exact name. I may add it here at a later date)

A bank ATM has the following basic functionality:

– Enter Pin Number
– Check balance
– Pay in Money
– Withdraw Money
– Print Mini-Statement
– Sign out

If I pop over to my bank branch, I get a few more functions but that’s nice and simple for now. In the UK, we have a system called ‘LINK’. Basically, this allows account holders of a LINK member bank to use basic functionality at another LINK member bank’s ATM for free. Naturally, this would have limited functionality since it can get quite busy on banking networks and you really want minimal traffic so the banks will want to provide basic functionality on their ATMs for LINK member account holders. So, how do we guarantee the same functionality on all ATMs? Every bank functions slightly differently to the other so what are we going to do? Yep, that’s right, we use an interface!

The interface could be structured as follows:


interface ILinkFunctions:
{
double balance;

void CheckPin();
void ShowBalance();
void WithdrawCash();
void PayInMoney();
}

If every bank implemented this interface for their ATM software when dealing with LINK customers, they all get the same functionality!!

This now means that when you use a LINK machine, you will have the same basic functions wherever you go. Not only can you use this to guarantee that certain functionality exists, you can also use the interface as a type when making use of the functionality in other parts of your code. Here’s a simple example of that in use:


public void SpecificLinkFunction(ILinkFunctions source)
{
--Implementation here--
}

The above code allows you to make use of the knowledge that ILinkFunctions has certain guarantees. Think of how you could be writing a game in XNA and you want to process ALL sprites rather than have to process individual categories of sprite (baddies, hero, bosses, bullets, etc.). If all these sprite classes implemented an interface, you could process all sprites of that type in one simple function that made use of the interface they all share! Doesn’t that make life so much easier?

I’ve barely touched the surface here and I’m waffling on but a nice little example involving pencils is online here

Good luck!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

C#, XNA – The problem with Monty

Ah! Monty Mole! That loveable character from the 1980s series of games for the Amstrad, Spectrum and Commadore. As some may already know, I’m in the process of remaking “Auf Wiedersehen Monty” with the outstanding help of Lobo and Infamous. Sadly, finding time to complete this while my work/financial situation is so bad at the moment is a bit of a problem. Despite needing to re-work the collision detection and pretty much finish the thing, it is gone quite well so far. I thought I’d share one of the interesting ideas that some people may not realise they can do in C# and XNA which is storing the state of the user controlled sprite as an enum! Here’s a snippit of code from the game:


// Deals with Stationary and moving for animation purposes
if ((((mCurrentState == MontyState.WalkingLeft) || (mCurrentState == MontyState.WalkingRight)) || ((mCurrentState == MontyState.ClimbingUp) || (mCurrentState == MontyState.ClimbingDown))) || (mCurrentState == MontyState.Stationary))

It looks a little complex doesn’t it? Simply translated, it basically checks whether the Monty character is walking left, walking right, climbing up, climbing down or stationary. I’m sure you could have worked that out but it is so much more readable like that isn’t it? Much more readable and efficient than creating loads of flags or a numerical variable with sokme kind of coded number representing the character’s status.

So… how did I do this? Well, I used an enum! The code is here:


public enum MontyState
{
Stationary,
WalkingLeft,
WalkingRight,
JumpLeft,
JumpRight,
JumpUp,
UpsideDown,
InCableCar,
ClimbingUp,
ClimbingDown,
SuperJumping,
FlyingPlane,
Dead
}

This now means I can create a variable like this:


public MontyState mCurrentState = MontyState.Stationary;

Whenever something happens, I change Monty’s state to whatever it should be and the program can react accordingly. I’m probably teaching some people how to suck eggs here but I did have a good think before I decided to take this approach. Making it public means you can use the status in other parts of the application too. You can even make it static if you wish.

Enjoy!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

C# – Accessing attributes directly in XML

Well hello and welcome to my blog.  God knows if it’ll be of any use to anyone but if it is, I’d appreciate a comment saying so.  It isn’t much but it’ll make me think that I do occasionally do something worthwhile for the world.

Right, onto the topic of the first post.  If, like me, you get pissed off with hunting the internet for an example of some code that does something similar to what you’re trying to achieve but never seem to find it, read on.  That’s pretty much the main reason I set this blog up;  to highlight minor (and major) issues in development that crop up from time to time and post a solution (even code, you never know) for others to make use of.

Anyway, the other day I was working on some code that processed some XML and I was required to produce some C# that extracted a particular value from this file.

Use LINQ I hear you cry!  Not in .NET 2.0 you can’t.  I hunted around for examples and, lo and behold, I found nothing of any real use.  Plenty of examples that use foreach loops to iterate through the many attributes and writes them out to the console but nothing exactly describing what I needed. (By the way, who the hell does that in the first place?  MSDN!  I’m looking at you here.  Producing piss-poor examples is no help to anyone!)

Anyway, onto the code.  Let’s take an example XML file like the following:

<?xml version=”1.0″?>
<TheDocument xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”>
<TheHeader Version=”3″ FileType=”1″ Size=”44″/>
<Data>
<DataRow>454,500,544,525,474,484,484,553</DataRow>
<DataRow>454,500,544,525,474,484,484,553</DataRow>
<DataRow>454,500,544,525,474,484,484,553</DataRow>
</Data>
</TheDocument>

Ok, it’s a bit crappy but it is an example.  Anyway, I need to access “FileType” from “TheHeader”.  How do I do it?

Here’s how:

// Create the XML Document
XmlDocument _xmlFile = new XmlDocument();

// Create an XmlTextReader to load the file
XmlTextReader reader = new XmlTextReader(@”C:\SampleFile.xml”);

// Load the file into the XML Document using the reader
_xmlFile.Load(reader);

// Set up an XML element and pop the document into it
XmlElement root = _xmlFile.DocumentElement;

// OK, now select that attribute
int _fileVersion = Int32.Parse(root.SelectSingleNode(“/TheDocument/TheHeader/@Version”).Value);

Although this example is fairly specific, you should be able to create a C# project, paste the code in and get it working quite quickly.  You will need to include the following using statements at the top though:

using System.Xml;
using System.IO;

You’d have to hunt high and low to find anything that useful on t’internet.

Anyway, please be gentle as it was my first post.  All feedback welcome and any suggestions for future posts would be nice too.

Toodle pip!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)