3

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

the second example does not work since SomeClass1 is the type of the property not the type of ISample and the first will throw an exception if ISample is of SampleA
then use constraints :) and I'm assuming things are public, his code shows it not-public.
I added some type checks for ntziolis - I wasn't showing the safe route, I was showing how to cast the objects. Clearly, some design should be added to make the code more reliable.
@user1299340 - do I get the answer accepted?!?! [always going for more SO points]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.