65.9K
CodeProject is changing. Read more.
Home

Dynamic Members in C#

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (9 votes)

Jan 10, 2006

viewsIcon

51127

downloadIcon

472

An article on how to add dynamic members to your objects at runtime.

Sample Image

Introduction

Very often, you have to inherit from classes even if there is only one more variable you have to add. Using this code, you will be able to add members dynamically at runtime.

Using the code

To get the advantage of dynamic members, you have to inherit your classes from Object. This class offers the interface to add members dynamically. The interface consists of only four functions.

class Object
{
    public bool setDynamicMember(string sName, object oObject);
    public object getDynamicMember(string sName);
    public bool addDynamicMember(string sName, object oObject);
    public bool removeDynamicMember(string sName); 
}

I think the names of the functions are self explanatory.

Points of Interest

Each dynamic member is represented by an instance of a storage class called dynamicMemberContainer.

class dynamicMemberContainer
{
    public string sName;
    public object oObject;
}

These instances are listed in an array (System.Collections.Arraylist).

History

This is the first version of the code, so there is no history.