I would like to call an explicit interface property by casting to a generic type. More specifically, here is the example I tried to make work:
public interface I1
{
double Value { get; set; }
}
public interface I2 : I1
{
// Hide value from I1 to use it as an explicit interface property.
new double Value { get; set; }
}
public class C1 : I2
{
// Exception because I only care about I2 explicit Value property.
double I1.Value { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
double I2.Value { get; set; }
}
public class ExampleClass<T> where T : I1
{
public double? SomeMethod(I1 i1)
{
if (i1 is T t)
return t.Value;
return null;
}
}
public static class Main
{
public static void Test()
{
var exampleClass = new ExampleClass<I2>();
var c1 = new C1();
((I2)c1).Value = 1;
exampleClass.SomeMethod(c1);
}
}
If I call Main.Test(), he will throw an exception because he will try to get the I1.Value property on c1. Why is that case ? It seems to me he should cast c1 to I2, thus return the I2.Value property.