473,416 Members | 1,764 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,416 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 17703
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.