Reputation: 1051
There is some duplicate of similar thread in stackoverflow but this is not exact same, so I post here again. Let's consider the following example.
public interface ILeft
{
void Move();
}
public class MoveableOject : ILeft
{
//without public we get an error
public void Move()
{
Console.WriteLine("Left moving");
}
}
class Program
{
static void Main(string[] args)
{
MoveableOject mo = new MoveableOject();
mo.Move();
Console.ReadKey();
}
}
All are fine. Now let's consider the explicit implementation of ILeft. Why does the commented line give above error message?
class MoveableOject : ILeft
{
void ILeft.Move()
{
Console.WriteLine("Left moving");
}
}
class Program
{
static void Main(string[] args)
{
MoveableOject mo = new MoveableOject();
// MoveableOject moWithErrorObject = (ILeft) new MoveableOject(); <--
((ILeft)mo).Move();
((ILeft)new MoveableOject()).Move();
Console.ReadKey();
}
}
Edit: 8th Nov/2015 MoveableOject in the error statement should be ILeft understandable, mistakenly I put it there. Why I post it the reason I could not explain it, let's use the object and passed to a method in the following way.
public static void ExpectDerivedPassedDerived(MoveableOject passedObject)
{
passedObject.Move();
}
Now if I call the method from Main should it work? But it does not because I have explicit implementation but if I implement with public keyword then this will be fine, I was looking an explanation of this.
ExpectDerivedPassedDerived(mo); //mo is MoveableOject type
Upvotes: 1
Views: 9355
Reputation: 1816
The error that you are observing has nothing to do with explicit implementation of ILeft
. Actually that's because of assignment compatibility
.
We can only assign more derived objects to less derived objects, not vice versa.
You cannot do:
MoveableOject moWithErrorObject = (ILeft) new MoveableOject();
As MoveableOject
is more derived than it's parent ILeft
.
You can get some details here.
Upvotes: 2
Reputation: 4249
You create a new MoveableOject
, cast it as ILeft
, and then you try to assing the ILeft
you got from cast to a MoveableObject reference. Compliler disagree, as expected
Ileft iLeftReference = getILeft();
MoveableOject mObj = iLeftReference; // same error
Upvotes: 2