LDNDeveloper

Andrew Pallant

     Senior IT Executive 


Donate To Support My Blog Donate if this post helped you. Coffee money is always welcomed!




Creating a Collection of Top-Level Class From Base Level Class

Physical Link: Creating a Collection of Top-Level Class From Base Level Class


When you have a class inherit another class, sometimes you want the base level class to create a collection of the top-level class.  In this blog I will demonstrate some basic inheritance and a little reflection trick.  Note the examples are in C#, but could easily be done in VB.NET

Why you may want to do this?  You may want to create a base class to handle all of your basic database functions from which your data layer classes will inherit to limit duplicate code.  In the base class you may create a “SELECT” function to return multiple rows of data.  The rows of data being returned are represented by the top-level class, for which you need a collection of the base level class.

You need two components or classes.  The first is to create your base class from which you will inherit later on.  In the base class you will create a method to generate a collection of the top-level class.  The example being used is passing in the size of collection to be returned, but you could have it being auto generated based on number of database rows.



public class BaseClass
{
public String FirstName { get; set; }

public BaseClass()
{
}

public ArrayList getCollection(String className, int limit)
{
ArrayList collection = new ArrayList();

Type t = Type.GetType(className); 
for ( int icount=0; icount < limit; icount++ )
{
object clss = Activator.CreateInstance(t);
((BaseClass)clss).FirstName = "Bob"; 
collection.Add(clss);
}

return collection;
}
}

The next part is to create a class that inherits the base class.  From this new class we are going to make a public function that will return the requested collection.  Remember; you could be returning class collection of data rows or another single purpose that could be represented by a class.


public class ClassInherit : BaseClass
{
public ClassInherit()
{
}

public ArrayList BuildCollection()
{
return getCollection("ClassInherit", 4);
}
}

If you have questions regarding this blog or the purpose of this blog, please feel free to contact me at www.unlatched.com or www.andrewpallant.com.

The post Creating a Collection of Top-Level Class From Base Level Class appeared first on LDNDeveloper.

Author:
Categories: Uncategorized


©2024 LdnDeveloper