Klyse
Klyse

Reputation: 69

C# use template type in foreign class

Is it possible to use a Template from a specific class in another class?

Example:

class DBObject<DataType>
{
    private string _name;
    private DataType _value;

    public DBObject()
    {
        _name = String.Empty;
    }

    public DBObject(string name)
    {
        this._name = name;
    }

    public DataType GetValue
    {
        get { return _value; }
        set { _value = value; }
    }
}

DataType is the Template I'm using in the class DBObject

My TestTbl Class contains the DBObject<DataType> elements.

class TestTbl : DBTableObjects 
{
    public DBObject<int> _id;
    DBObject<string> _name;
    DBObject<string> _address;

    TestTbl()
    {
        AddDBTableObject(_id = new DBObject<int>("id"));
    }
}

The AddDBTableObject function adds the element to a List in the DBTableObjects Class.

class DBTableObjects
{
    List<DBObject> ls;

    public DBTableObjects()
    {
        ls = new List<DBObject>();
    }

    protected void AddDBTableObject(DBObject obj)
    {
        ls.Add(obj);
    }
}

Problem: The List<DBObject> requires also a templatetype for the DBObject instance. How can I use the DataType from the DBObject Class here?

Upvotes: 0

Views: 49

Answers (1)

Zein Makki
Zein Makki

Reputation: 30022

Problem is in List<DBObject> ls; It needs to be generic:

class DBTableObjects
{
    List<DBObject<int>> ls;

    public DBTableObjects()
    {
        ls = new List<DBObject<int>>();
    }

    protected void AddDBTableObject(DBObject<int> obj)
    {
        ls.Add(obj);
    }
}

Upvotes: 1

Related Questions