Home > database >  C# - Adding specific type to generic
C# - Adding specific type to generic

Time:12-20

Im want to make method more user comfortable in method with Generic T

public class foo_Class
    {
        public My_Class(object ob, string foo)
        {
            this.ob = ob;
            this.foo = foo;
        }
        public object ob { get; set; }
        public string foo { get; set; }
    }

so when im adding foo_Class to Dictionary for example, we have to write like this.

Dictionary<string, foo_Class> foo_Dictionary = new Dictionary<string, foo_Class>();

foo_Dictionary.Add("foo", new foo_Class(Value1, "fo"));

but i just want to write like this using override,

Dictionary<string, My_class> My_Dictionary = new Dictionary<string, My_class>();

My_Dictionary.Add("foo", Value1, "fo");
...

So, help me to solve this prob.

Thx.

CodePudding user response:

If I understand correctly, you just want to extend Dictionary<string, MyClass>:

// some names are renamed to follow C# conventions
public class MyDictionary : Dictionary<string, MyClass> {
    public void Add(string key, object value, MyEnum flags) {
        Add(key, new MyClass(value, flags));
    }
}

Then you would be able to do:

var dict = new MyDictionary();
dict.Add("myClass1", myValue1, MyEnum.Enum1);
dict.Add("myClass2", myValue2, MyEnum.Enum2);

If you only plan on adding methods to Dictionary<string, MyClass>, an extension method is a better choice.

public static class MyClassDictionaryExtensions {
    public static void Add(
        this Dictionary<string, MyClass> dict, 
        string key,  
        object value, 
        MyEnum flags) {
        dict.Add(key, new MyClass(value, flags));
    }
}

Usage:

var dict = new Dictionary<string, MyClass>();
dict.Add("myClass1", myValue1, MyEnum.Enum1);
dict.Add("myClass2", myValue2, MyEnum.Enum2);
  • Related