Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
XML
I have different objects like :

class Teacher
{
  public int ID {get, set};
  public string Subject {get, set};
  public string Designation {get, set};
}

class School
{
  public int ID {get, set};
  public string Type {get, set};
}

I have two functions FillSchool(dictTeacher) and FillTeacher(dictSchool) as :

FillSchool(Dictionary<string,Teacher> dictTeacher)
{ dicTeacher.ID= 1}

FillTeacher(Dictionary<int, School> dictSchool)
{dictSchool.ID = 2}



Now I want to make a single function ( using generics or some better way) which fills values in these objects.
Posted

1 solution

This is really simple. For example:
C#
using System.Collections.Generic;

//...

class SomeClass<KEY_TYPE, VALUE_TYPE> {

    Dictionary<KEY_TYPE, VALUE_TYPE> myDictionary =
        new Dictionary<KEY_TYPE, VALUE_TYPE>();

    // just for example
    internal void Add(KEY_TYPE key, VALUE_TYPE value) {
        //...
        myDictionary.Add(key, value); // may throw exception if the key is already found
    }

    // alternative without exceptions:
    // will return either new or already existing value:
    internal VALUE_TYPE AddOrRetrieve(KEY_TYPE key, VALUE_TYPE value) { 
        if ((myDictionary.TryGetValue(key, out value))
            return value; // already existing value
        myDictionary.Add(key, value); // due to the check above, won't throw exception
                                      // (unless you add in some other thread, too)
        return value; // new value
    }

    // and so on...

}


I hope my comments make this usage clear.

—SA
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900