Generics when they aren't needed?

Hi,

I’ve been searching the web to better understand this and I simply can’t find the answer I need, so I’m turning to the Unity community with a Unity-specific example.

I am working with Generics for the first time and I have created a class which extends Dictionary. The normal way to do this with generics is:

public class MyDict<TKey, TValue> : Dictionary<TKey, TValue>
{
    ...

…but I know exactly what my two types are, AND I am using a method of Rect in one of my methods, so I tried this and it works exactly as above, but I can use Rect methods in my methods…

public class MyDict<string, UnityEngine.Rect> : Dictionary<string, Rect>
{
    ...

Note I HAVE to put UnityEngine.Rect in the first spot and then C# seems to be ok with all the plain 'Rect’s from then on…what the?..

It seems strange that, when I already know the types, that I have to use this as a Generic like so:

MyDict<string, Rect> myDict = new MyDict<string, Rect>();

It seems like I should be able to make a strongly typed dictionary and call it like this:

MyDict myDict = new MyDict()

Can anyone explain to me, first, why the first two class declarations both work and what I am really doing by adding my own types instead of keeping it ‘generic’, and second, assuming I am explaining what I am trying to do, do I just have to use it as a Dictionary, generics and all, or is there a more simple way to create a strongly typed key/value struct.

Cheers,

OK, well the above didn’t cause any errors in Visual C#, but unity says:

It turns out the second way of doing it in my original post does NOT work.

I can’t figure out a way to add a method to my Dictionary which allows me to work with a type, such as Rect.

Now I have to put my Method in another place which isn’t ideal, but will work.

I am very interested in understanding why all of this is necessary.

Try next

class MyDict: Dictionary<string, Rect> {
  ...
}
MyDict dict = new MyDict();
dict["rect"] = new Rect(0, 0, 1, 1);

:shock: It works. I think I love you.

Welcome :slight_smile: