out with inherited objects

R

RichB

Something I don't understand why it is happening, or how to fix it.....

I have a teacher class which inherits from person.
And within a search class have a search method with the following:


Dictionary<String, Person> people = new Dictionary<String, Person>();
people.Add("a", new Teacher("Bob", "Smith");

Teacher teach;
if (!people.TryGetValue("Jane", out teach)
{
teach = new Teacher ("Jane", "Jones");
}


Error 1 The best overloaded method match for
'System.Collections.Generic.Dictionary<string,DataTier.VOs.VO>.TryGetValue(string,
out DataTier.VOs.VO)' has some invalid arguments C:\Documents and
Settings\Richard Box\My Documents\Visual Studio
2005\Projects\DataTier\DataTier\DataAccess\EventDAO.cs 307 26 DataTier

Error 2 Argument '2': cannot convert from 'out DataTier.VOs.EventVO' to 'out
DataTier.VOs.VO' C:\Documents and Settings\Richard Box\My Documents\Visual
Studio 2005\Projects\DataTier\DataTier\DataAccess\EventDAO.cs 307 57
DataTier

But Teacher is a Person, so why can an implicit conversion not be performed?

Is there a way around this other than not using the TryGetValue() method?

Thanks,
Richard
 
R

RichB

Sorry, created my example from my head, then cut and pasted the errors.....
In the errors read
VO = Person,
EventVO = Teacher.

Sorry hope this clears any confusion.
Richard
 
J

Jon Skeet [C# MVP]

But Teacher is a Person, so why can an implicit conversion not be performed?

Suppose your dictionary had a person *other* than a teacher in...

The simple example of this is something like:

void DoSomething (ref object x)
{
x = new object();
}

string y = "hello";
DoSomething (ref y);

Something's got to go bang somewhere, otherwise y has a reference to a
non-string object.
The compiler keeps this safe.
Is there a way around this other than not using the TryGetValue() method?

Yes, use a temporary local variable and then cast.

Jon
 
R

RichB

Sorted thanks.


Jon Skeet said:
Suppose your dictionary had a person *other* than a teacher in...

The simple example of this is something like:

void DoSomething (ref object x)
{
x = new object();
}

string y = "hello";
DoSomething (ref y);

Something's got to go bang somewhere, otherwise y has a reference to a
non-string object.
The compiler keeps this safe.


Yes, use a temporary local variable and then cast.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top