I am trying to learn generic types and I’ve written this code:
public class MyProp<TDictonary, TValor>
{
private List<TDictonary> MyDictionary = new List<TDictonary>();
private List<TValor> TValue = new List<TValue>();
public MyProp<TDictonary, TValue> Search(TDictonary dictionary)
{
MyProp<TDictonary, TValor> dic = new MyProp<TDictonary, TValor>();
var test = MyDictionary.FirstOrDefault(item => item == dictionary);
return dic;
}
So I tried to create something like a C# Dictionary. What I tried to do was to associate TDictionary and TValue to Lists, add them to my generic type and return MyProp with its content. I also plan to add other methods like Add, Remove, etc, but if I’m not able to perform a simple search within a list I certainly won’t be able to go any further.
Does anyone know if I’m going down the right path? If not, could you point to the right path?
Thank you.
You do know about
System.Collections.Generic.Dictionary<TKey, TValue>though, right?Anyway, I’m not sure what your generics (or even the type) are actually meant to represent (give them clearer names!), so I cannot exactly tell you what you have to change to actually search on your dictionary.
However there are a few hints:
dic, do nothing on it and then simply return that – regardless of what you do previously.MyDictionarybut completely ignore theTValuefield.camelCase, i.e. starting a lower case character.TValueis very confusing, due to the startingT. That is usually reserved for generic types only.That’s because the type is a generic type without any restrictions. So it can either be a reference type or a value type, as such the compiler cannot decide about which comparison to do for the
==operator. A simple, but maybe restricting, fix would be to specify a base type that is either a value type, or a reference type: