473,242 Members | 1,509 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,242 software developers and data experts.

Dictionary<> and Inheritance


I want to expose a property of Dictionary<string, MyAbstractClass>.

I tried to do it this way:

private Dictionary<string, MyChildClass> _dictionary;

public Dictionary<string, MyAbstractClass>
{
get { return _dictionary; } //error: no implicit conversion.
}

How can I have a privay dictionay that uses an inheritied class, but
expose that dictionary as the base type?
--Brian
Feb 10 '06 #1
8 17662
No, and here is why.

Let's say that you could expose a dictionary of MyChildClass objects as
a dictionary of MyAbstractClass objects.

public class MyChildClass : MyAbstractClass { ... }
public class MyChildClass2 : MyAbstractClass { ... }

private Dictionary<string, MyChildClass> _dictionary;

public Dictionary<string, MyAbstractClass> Dict
{
get { return _dictionary; } //error: no implicit conversion.
}

Now, outside this class, you say

Dictionary<string, MyAbstractClass> theDictionary = myObject.Dict;
theDictionary["Bruce"] = new MyChildClass2(...);

That last line seems perfectly legal to the compiler, but would have to
fail at runtime, because the actual dictionary returned by
myObject.Dict is not a dictionary of "anything that inherits from
MyAbstractClass". It is, rather a dictionary of a specific subclass of
MyAbstractClass, called MyChildClass.

By allowing the return of a dictionary of a class farther up the
hierarchy, you've lost compile-time type safety, which is what generics
are trying to give you in the first place.

Feb 10 '06 #2
Brian P <no@email.com> wrote:
I want to expose a property of Dictionary<string, MyAbstractClass>.

I tried to do it this way:

private Dictionary<string, MyChildClass> _dictionary;

public Dictionary<string, MyAbstractClass>
{
get { return _dictionary; } //error: no implicit conversion.
}

How can I have a privay dictionay that uses an inheritied class, but
expose that dictionary as the base type?


You can't. There's no covariance like that on generic types. If you
could do that, consider the following code:

Dictionary<string, MyAbstractClass> foo = YourProperty;
MyOtherChildClass bar = new MyOtherChildClass();
foo["hello"] = bar;

Now, the actual dictionary is only meant to contain MyChildClass values
- but I've just broken that!

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 10 '06 #3
Jon Skeet [C# MVP] wrote:

You can't. There's no covariance like that on generic types. If you
could do that, consider the following code:

Dictionary<string, MyAbstractClass> foo = YourProperty;
MyOtherChildClass bar = new MyOtherChildClass();
foo["hello"] = bar;

Now, the actual dictionary is only meant to contain MyChildClass values
- but I've just broken that!

I must be doing something wrong in my design / thinking.

To the outside world, I want the Dictionary<string, MyAbstractClass> to
be "read-only". So, I guess I'm not worried about the problem you point
out.
But, I realize that I'm surely doing something poor:

I have an interface that several classes implement. The interface
requires Dictionary <string, MyAbstractClass>. But the classes that
implement that interface, their interal workings are going to use
ChildClasses of MyAbstractClass. And so long as the only usage of
ChildClasses are interally, I can't see how exposing the dictionary as
MyAbstractClass is "bad".
--Brian




Feb 10 '06 #4
Jon Skeet [C# MVP] wrote:

You can't. There's no covariance like that on generic types. If you
could do that, consider the following code:

Dictionary<string, MyAbstractClass> foo = YourProperty;
MyOtherChildClass bar = new MyOtherChildClass();
foo["hello"] = bar;

Now, the actual dictionary is only meant to contain MyChildClass values
- but I've just broken that!

I must be doing something wrong in my design / thinking.

To the outside world, I want the Dictionary<string, MyAbstractClass> to
be "read-only". So, I guess I'm not worried about the problem you point
out.
But, I realize that I'm surely doing something poor:

I have an interface that several classes implement. The interface
requires Dictionary <string, MyAbstractClass>. But the classes that
implement that interface, their interal workings are going to use
ChildClasses of MyAbstractClass. And so long as the only usage of
ChildClasses are interally, I can't see how exposing the dictionary as
MyAbstractClass is "bad".
--Brian



Feb 10 '06 #5
Brian P <no@email.com> wrote:
Now, the actual dictionary is only meant to contain MyChildClass values
- but I've just broken that!
I must be doing something wrong in my design / thinking.

To the outside world, I want the Dictionary<string, MyAbstractClass> to
be "read-only". So, I guess I'm not worried about the problem you point
out.


Okay - but there's nothing to stop clients from *trying* to do that.
You're not exposing it in a read-only way (not that I can see any read-
only interfaces that are easily exposed in the generic collections
provided by the framework...)
But, I realize that I'm surely doing something poor:

I have an interface that several classes implement. The interface
requires Dictionary <string, MyAbstractClass>. But the classes that
implement that interface, their interal workings are going to use
ChildClasses of MyAbstractClass. And so long as the only usage of
ChildClasses are interally, I can't see how exposing the dictionary as
MyAbstractClass is "bad".


I entirely understand where you're coming from, but I can't immediately
think of any way of doing it with generics.

Do the internal workings definitely need to know they they'll be using
ChildClass, other than when they're putting the entries in?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 10 '06 #6
Brian P <no@email.com> wrote:

<snip>
I must be doing something wrong in my design / thinking.

To the outside world, I want the Dictionary<string, MyAbstractClass> to
be "read-only". So, I guess I'm not worried about the problem you point
out.


I've thought of an alternative. Rather than exposing a whole
Dictionary<string,MyAbstractClass> would it be possible to expose just
a property:

public MyAbstractClass this[string key];

? You could easily implement that in your class, just by returning
_dictionary[key]; and you'd be guaranteed that it would be exposing it
in a read-only way.
Alternatively, you could have:
class ReadOnlyDictionary<K,V1,V2> : IDictionary<K,V1>
where V2 : V1
{
Dictionary<K,V2> dictionary;

public V1 this [K key]
{
get { return dictionary[key]; }
set { throw new UnsupportedOperationException(); }
}

// etc - implement the rest of the appropriate IDictionary
// properties
}

You could then use:

public IDictionary<string, MyAbstractClass>
{
get { return new
ReadOnlyDictionary<string, MyAbstractClass, ChildClass>
(dictionary);
}

I *think* that would work - and would actually be quite neat (and very
reusable). You could do the same for List if you ever needed to.

My guess is that *someone* has actually already done this and published
it as open source... I can't be the first to think of it.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 10 '06 #7
Jon Skeet [C# MVP] wrote:

I entirely understand where you're coming from, but I can't immediately
think of any way of doing it with generics.

=) so I'm not completey dumb.


Do the internal workings definitely need to know they they'll be using
ChildClass, other than when they're putting the entries in?


Yes, they do. So, for now, I have a private dictionary of <string,
MyAbstractClass> and in the internal workings, I cast to MyChildClass:

((MyChildClass)_myDictionary["foo"]).ChildSpecificPropertyOrMethod
This lets me expose the dictionary as MyAbstractClass but I still can
"work" with the ChildClass internally. Though, I admit this doesn't
seem ideal.

--Brian
Feb 10 '06 #8
Jon Skeet [C# MVP] wrote:

I've thought of an alternative. Rather than exposing a whole
Dictionary<string,MyAbstractClass> would it be possible to expose just
a property:

public MyAbstractClass this[string key];

? You could easily implement that in your class, just by returning
_dictionary[key]; and you'd be guaranteed that it would be exposing it
in a read-only way.

I *think* that would work - and would actually be quite neat (and very
reusable). You could do the same for List if you ever needed to.

My guess is that *someone* has actually already done this and published
it as open source... I can't be the first to think of it.

Yes! This sounds perfect! You are awesome ... I see you all over these
newsgroups and I always read your posts. Most of the time you are
talking about things over my head, but I usually learn something new
from you.

Thanks again,

--Brian
Feb 10 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to...
1
by: Eran | last post by:
Hi, I have a huge data structure, which I previosly stored in a Dictionary<int, MyObj> MyObj is relatively small (2 int, 1 DateTime, 1 bool). The dictionary I am using is quite large...
7
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any way to convert from a dictionary to a list...
4
by: Peter K | last post by:
Hi are there any benefits in using StringDictionary over Dictionary<string, string? It appears they achieve the same thing... (I could be wrong of course). thanks, Peter
4
by: Mark S. | last post by:
Hello, I have a series of changing string IDs that are loaded dynamically a couple times a minute. I need to associate each ID with a different static class so later on in the app's lifecycle it...
8
by: Peter Larsen [CPH] | last post by:
Hi, How do i concat two dictionaries aka the following sample: Dictionary<int, stringa; Dictionary<int, stringb; b.Add(a); What is the easiest way to concat two dictionaries ??
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.