The easiest way to look at building objects is by first thinking about the logical structure of your data. Using the idea of a Foo we shall construct a logical Data Hierarchy of objects.
Start at the very top of the tree, then move down, firstly the Foo class.
using System;
namespace BusinessObjects
{
public class Foo
{
private int _Id = -1;
public string Id
{
get
{
return _Id;
}
set
{
_Id = value;
}
}
public Foo()
{
}
}
}
Initially there is just one property on the object, this is enough for us to be able to Identify which Foo the Class is. Also it is handy to be able to pre-populate the properties on the class, this is achieved by using constructors.
namespace BusinessObjects
{
public class Foo
{
private int _Id = -1;
public string Id
{
get
{
return _Id;
}
set
{
_Id = value;
public Foo()
{
}
public Foo(int FooId)
{
_Id = FooId;
}
}
}
We now have some code that is simple to understand and very easy to use, some sample usage is here: -
private void DoSomething()
{
BusinessObjects.Foo C = new BusinessObjects.Foo(500002112);
Console.WriteLine(C.Id);
}
The Strongly Typed Collection
Having one of an object is useful, but being able to group objects of the same type together in to a collection is essential. What follows is the code to create an object in which to store the Foo objects.
using System;
using System.Collections;
namespace BusinessObjects
{
public class FooCollection : CollectionBase
{
public Foo this[int index]
{
get { return (Foo) this.List[index]; }
set { this.List[index] = value; }
}
public void Add(Foo myFoo)
{
if (!DoesFooExist(myFoo.Id))
{
this.InnerList.Add(myFoo);
}
}
public bool DoesFooExist(int FooId)
{
bool flag = false;
foreach(Foo C in this)
{
if (C.Id == FooId)
{
flag = true;
break;
}
}
return flag;
}
public FooCollection ()
{
}
}
}
What we have above is a Class that inherits from CollectionBase, we’ve added an Indexer, an Add Method and a Method to check if a Foo object is already contained within the collection.
What follows is sample usage of the Collection object.
private void DoSomethingElse()
{
BusinessObjects.Foo Foo1 = new BusinessObjects.Foo(1);
BusinessObjects.Foo Foo2 = new BusinessObjects.Foo(2);
BusinessObjects.FooCollection CC = new BusinessObjects.FooCollection();
Console.WriteLine("Foo in the Collection? : " + CC.DoesFooExist(Foo1.Id));
CC.Add(Foo1);
CC.Add(Foo2);
Console.WriteLine("Foo in the Collection now ? : " + CC.DoesFooExist(Foo1.Id));
Console.WriteLine("Foo in the Collection using an Index? : " + Convert.ToString(Foo2.Id == CC[0].Id));
Console.WriteLine("Foo in the Collection using an Index? : " + Convert.ToString(Foo2.Id == CC[1].Id));
}
The result from the above would be: -
Foo in the Collection? : False
Foo in the Collection now ? : True
Foo in the Collection using an Index? : False
Foo in the Collection using an Index? : True