Reputation: 11090
I have a base class that has the following property:
public virtual Dictionary<String, int> activity
{
get;
set;
}
A derived class overrides this as such:
Dictionary<string, int> myActivity = new Dictionary<string, int>()
{
{"result", 5},
{"total", 6}
};
public override Dictionary<string, int> activity
{
get
{
return myActivity;
}
}
I want to call the override dictionary from within the same assembly of the base class, but a different class.
so for example from Class2 I want to call:
Class1 c = new Class1();
And then try to access dictionary as such:
c.activity["result"]
I get an error saying it's not within the dictionary?
The derived class is in another assembly...dll file.
Any ideas?
Thanks.
Upvotes: 0
Views: 234
Reputation: 2462
You've created an instance of Class1 which if I'm interpreting the question correctly, is your base class (including the class declarations would be helpful). In order for your object c to use the dictionary from Class2, it needs to be created as an instance of Class2.
Your code would then look like this:
Base class:
class Class1
{
public virtual Dictionary<String, int> activity
{
get;
set;
}
}
Derived class:
class Class2
{
Dictionary<string, int> myActivity = new Dictionary<string, int>()
{
{"result", 5},
{"total", 6}
};
public override Dictionary<string, int> activity
{
get
{
return myActivity;
}
}
}
And then the calling code
Class1 c = new Class2();
At this point, c.activity["result"] will contain the expected result.
Upvotes: 0
Reputation: 29244
If you don't have an dictionary instance declared in Class1 then mark the property abstract. If you do, then just add the value "result" to it. Think clearly on who owns the data between Class1 and Class2. In fact maybe Class1 needs to be just an interface here if it does not intent to actually allocate any data.
Upvotes: 0
Reputation: 50712
Class1 c = new Class2();
c.activity["result"]
will work you override activity property in Class2 not in Class1
Upvotes: 2
Reputation: 1061
It doesnt sound like the Class1 c = new Class1();
is the same instance as class where you have instantiated the Dictionary
To be able to access the Dictionary
property with the value, the class you have instantiated must be either the class which instantiates the Dictionary
, or a class that derives from it.
Upvotes: 1