[Proposal] Multi-interface type #5263
-
SummaryAllow to create multi-interface type variables, fields, parameters and so on. MotivationSome times it may be useful to work with some object knowing it implements more than one interface. Implementing aggregating interface in this case can be overengineering. Current situation (C# 9)interface IHasX
{
int X { get; set; }
}
interface IHasY
{
int Y { get; set; }
}
class Foo
{
private readonly IHasX x;
private readonly IHasY y;
// 'x' and 'y' can't be specific type object, but shoud be same object, implementing both interfaces
public Foo(IHasX x, IHasY y)
{
if(!ReferenceEqual(x, y))
throw new InvalidOperationException("x and y shoud be same object");
// can't be stored in single field;
this.x = x;
this.y = y;
}
void DoSome(object obj)
{
if (obj is IHasX x and IHasY y)
{
x.X++;
y.Y++;
}
}
}Possible workaround (requires rewriting of existing code)interface IHasXY: IHasX, IHasY
{
}
class Foo
{
private readonly IHasXY xy;
public Foo(IHasXY xy)
{
this.xy = xy; // can be stored in single field.
}
void DoSome(object obj)
{
if (obj is IHasXY xy)
{
xy.X++;
xy.Y++;
}
}
}With multi-inerface typesclass Foo
{
private readonly (IHasX, IHasY) xy;
// 'x' and 'y' can't be specified as 'solid' type, guarantee single object, implementing both interfaces
public Foo((IHasX, IHasY) xy)
{
this.xy = xy; // can be stored in single field.
}
void DoSome(object obj)
{
if (obj is (IHasX, IHasY) xy)
{
xy.X++;
xy.Y++;
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
|
If #399 is realised, the syntax for the multi-interface type would be |
Beta Was this translation helpful? Give feedback.
-
|
What's wrong with using generics? public interface HasX
{
void X();
}
public interface HasY
{
void Y();
}
public class C {
public void Perform<T>(T t)
where T: HasX, HasY
{
t.X();
t.Y();
}
} |
Beta Was this translation helpful? Give feedback.
-
|
It wouldn't work for constructors, which can't be generic. |
Beta Was this translation helpful? Give feedback.
If #399 is realised, the syntax for the multi-interface type would be
IHasX & IHasY