Object initializer with explicit interface in C#
-
24-09-2019 - |
Question
How can I use an object initializer with an explicit interface implementation in C#?
public interface IType
{
string Property1 { get; set; }
}
public class Type1 : IType
{
string IType.Property1 { get; set; }
}
...
//doesn't work
var v = new Type1 { IType.Property1 = "myString" };
Solution
You can't. The only way to access an explicit implementation is through a cast to the interface. ((IType)v).Property1 = "blah";
You could theoretically wrap a proxy around the property, and then use the proxy property in initialization. (The proxy uses the cast to the interface.)
class Program
{
static void Main()
{
Foo foo = new Foo() { ProxyBar = "Blah" };
}
}
class Foo : IFoo
{
string IFoo.Bar { get; set; }
public string ProxyBar
{
set { (this as IFoo).Bar = value; }
}
}
interface IFoo
{
string Bar { get; set; }
}
OTHER TIPS
Explicit interface methods/properties are private (this is why they cannot have an access modifier: it would always be private
and so would be redundant*). So you can't assign to them from outside. You might as well ask: how can I assign to private properties/fields from external code?
(* Though why they didn't make the same choice with public static implicit operator
is another mystery!)