C # - Create class and instantiate object
8 03 2008// A very simple class
namespace C3
// Give this namespace so that when referenced in other projects, developers needn’t fully qualify
{
public class Chapter_3
// The name of the class so when users might like to instatiate
{
private string psName;
// dimentioned space for a string to be stored privatly
static void main()
{
// this is the entry point for this class
}
public string gsName
// This is a public property inside this class
// the get and set simply use the private string to store data
{
get
{
return psName;
}
set
{
psName = value;
}
}
}
}
Once I had this is wasn’t much use and so I used the old trick from VB where you have a master project that never gets released but serves as the driving GUI in all testing. So I set up a new project, a Windows Form and referenced the above project in this. I can now test this class works and even run it in the debug mode. Very nice
// This is form class set up in VB Express 2008
// I have set this as the sole class in the project
// VERY IMPORTANT in this project I have added a refernece to my own class; Chapter3
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
// All of the above are the CLI or .NET in this instance
// All are class’s provided and by addin the using command we can use these class’s without fully qualifying the statment
using C3;
// I have a class that I have built with the namespace C3. This using command will mean I dont need to fully qualify
// This will only work becuse I have referenced this project in the references of thsi project
namespace Executable_Project
// This is the name of the project and by having this namespace it can be used in other class’s by making the link
// when the other class has the using command
{
public partial class Form1 : Form
{
public Form1()
{
// This is the entry point for this class
// The only instruction is to initialise the form
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// This is a private routine inside this class, the void means that nothing is returned
Chapter_3 oChapter_3 = new Chapter_3();
// The says. dimention me space for a new instance of the Chapter_3 class (fully qualified is c3.chapter3)
// make me a new chapter_3 and give is the object name of oChanpter3
oChapter_3.gsName = “alex crossley”;
// The oChapter_3 has a property called gsName that we will set to alex crossley
MessageBox.Show(oChapter_3.gsName);
// we will now get the property from the object and show it in a form
}
}
}