1

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.

1
  • 1
    I really wish I understood what you're asking. Can you please read How to Ask and minimal reproducible example and then, based on what you've read, edit your question to make it clearer? Commented Dec 20, 2022 at 7:57

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

wow. i didnt know about extension method. thx for new knowledge

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.