Reputation: 43
I am trying to change the property type in interface implementation class using explicit interface implementation.
interface ISample
{
object Value { get; set; }
}
class SampleA : ISample
{
SomeClass1 Value { get; set; }
object ISample.Value
{
get { return this.Value; }
set { this.Value = (SomeClass1)value; }
}
}
class SampleB : ISample
{
SomeClass2 Value { get; set; }
object ISample.Value
{
get { return this.Value; }
set { this.Value = (SomeClass2)value; }
}
}
class SomeClass1
{
string s1;
string s2;
}
But when I need to pass in interface obj in a function, I cant access the objects of SomeClass1 or SomeClass2.
For eg:
public void MethodA(ISample sample)
{
string str = sample.Value.s1;//doesnt work.How can I access s1 using ISample??
}
I don't know if this is understandable, but I cant seem to get an easier way to explain this. Is there a way to access the properties of SomeClass1 using interface ISample?
Thanks
Upvotes: 3
Views: 165
Reputation: 4561
That is because you've received the object as the interface, so it doesn't know about the class's new property type. You would need to:
public void MethodA(ISample sample)
{
if (sample is SampleA)
{
string str = ((SampleA)sample).Value.s1;
}
}
A better solution might be to use the visitor pattern - which would have implementations for handling the different ISample's.
Upvotes: 1