Reputation: 15
short description of my problem. I have passed generic object(interface) as parameter to my method. I need to call some method that will be common for subset of objects that implement my interface. I do not want to "have if() then" for each type of object there. let's call the interface IVehicles.
public interface IVehicle
{
Object SomeValue { get; }
}
public class Car : IVehicle{ //some code here}
It does not make sense to add method to IVehicle due to not sharing all logic.
I need to call SomePersonalValue only on subset of IVehicle. So I implemented another interface IPersonalVehicle and extended my objects:
public interface IPersonalVehicle
{
long SomePersonalValue { get; }
}
public class Car : IVehicle, IPersonalVehicle {}
public class MotorBike : IVehicle, IPersonalVehicle {}
Now I have my method
public void Call(IVehicle vehicle)
{
Object someIrrelevantObject = vehicle.SomeValue;
//here my change begins
IPersonalVehicle personalVehicle = (IPersonalVehicle)vehicle;
long somePersonalValue = personalVehicle.SomePersonalValue;
}
the problem is that it raises Unable to cast object Car to interface IPersonalVehicle.I have also tried to extend my interface by IVehicles and the resilt is the same.
public interface IPersonalVehiclee : IVehiclee
{
long SomePersonalValue { get; }
}
What I am doing wrong?
EDIT - SOLVED I forgot or somehow lost in code editation to to extend my Car and Motorbike by IPersonalVehicle lol, so this solution works! Thanks anyway!
Upvotes: 1
Views: 1437
Reputation: 630
If you post your question correctly, it works fine:
class Program
{
static void Main()
{
Call(new Car());
Call(new MotorBike());
}
public static void Call(IVehicles vehicle)
{
Object someIrrelevantObject = vehicle.SomeValue;
//here my change begins
IPersonalVehicles personalVehicle = (IPersonalVehicles)vehicle;
long somePersonalValue = personalVehicle.SomePersonalValue;
}
}
public interface IVehicles
{
Object SomeValue { get; }
}
public interface IPersonalVehicles
{
long SomePersonalValue { get; }
}
public class Car : IVehicles, IPersonalVehicles
{
public long SomePersonalValue => long.MinValue;
public object SomeValue => "car value";
}
public class MotorBike : IVehicles, IPersonalVehicles
{
public long SomePersonalValue => long.MaxValue;
public object SomeValue => "motorbike value";
}
Upvotes: 1
Reputation: 103
I think that if you are using both interfaces, you could just inject IPersonalVehicles
(which extend IVehicles
). You aren't allowed to cast one interface in other because it doesn't make sense.
Try to think on this: IPersonalVehicles
has its own properties (and methods) and same for IVehicles
. So, how could you cast them? Remember that casting is based on inheritance
Let me know if I help you!
Upvotes: 0