Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary - inherited classes

Tags:

c#

dictionary

I have a (hopefully) simple question:

I have some classes:

class Foo
class Foo1 : Foo
class Foo2 : Foo

I have two dictionaries:

Dictionary<int, Foo1> dic1 

Dictionary<int, Foo2> dic2

And I have a method:

private static int Method(Dictionary<int, Foo>)

and a method call:

Method(dic1);

but now I get the error that I can't convert Dictionary<int, Foo1> to Dictionary<int, Foo>.

How do I solve this problem?

Thank you :)

like image 875
BDevGW Avatar asked Oct 20 '18 11:10

BDevGW


People also ask

How do you inherit a dictionary in Python?

In Python, you can do this by inheriting from an abstract base class, by subclassing the built-in dict class directly, or by inheriting from UserDict . In this tutorial, you'll learn how to: Create dictionary-like classes by inheriting from the built-in dict class.

What is __ dict __ in Python?

The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.

How many classes are inherited?

Although classes can inherit only one class, they can implement multiple interfaces.

Are class methods inherited?

Yes, they can be inherited.


Video Answer


1 Answers

Generics, with a constraint of Foo should do it

public class Foo { }
public class Foo1 : Foo { }
public class Foo2 : Foo { }

public class SomeClass
{    
   public static int Method<T>(Dictionary<int, T> dict) where T : Foo
   {
      ...
   }
}

Additional Resources

Constraints on type parameters (C# Programming Guide)

Constraints inform the compiler about the capabilities a type argument must have. Without any constraints, the type argument could be any type. The compiler can only assume the members of Object, which is the ultimate base class for any .NET type.

...

By constraining the type parameter, you increase the number of allowable operations and method calls to those supported by the constraining type and all types in its inheritance hierarchy. When you design generic classes or methods, if you will be performing any operation on the generic members beyond simple assignment or calling any methods not supported by System.Object, you will have to apply constraints to the type parameter.

...

For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.

like image 156
TheGeneral Avatar answered Nov 10 '22 01:11

TheGeneral