Cast to two interfaces #4344
-
I have a generic type that I cannot control that implements multiple interfaces (lets call it So something like this. It would be great if public interface A { }
public interface B { }
public interface C<T> { }
public interface D : A, B { }
public class Source<T> : A, B, C<T> { }
public class Target<T> where T : A, B { /*Constructor and usage of A and B members here*/ }
static void Main()
{
Source<int> s = new();
Converter(s);
}
static void Converter(object obj)
{
if (obj is D d) // false
{
new Target(d);
}
else if (obj is A && obj is B) // true
{
new Target(???);
}
} PS: Method where this logic is located accepts |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
At first it sounds like you want Shapes/Roles (#164/#1711), but in playing around a bit with your sample you really don't need any of that to get it working. |
Beta Was this translation helpful? Give feedback.
-
This compiles: public interface A { }
public interface B { }
public interface C<T> { }
public interface D : A, B { }
public class Source<T> : A, B, C<T> { }
public class Target<T> where T : A, B {
readonly T _value;
public Target(T value) {
_value = value;
}
public void DoWork() {}
}
public static class TargetCreator {
public static Target<T> Create<T>(T value) where T : A, B => new Target<T>(value);
}
public class M {
static void Main()
{
Source<int> t = new();
if (t is D d) // false
{
TargetCreator.Create(d).DoWork();
}
else if (t is A && t is B) // true
{
TargetCreator.Create(t).DoWork();
}
}
} |
Beta Was this translation helpful? Give feedback.
-
See #399 Intersection types for interfaces. |
Beta Was this translation helpful? Give feedback.
This compiles: