i want to know which if1 and if2 and w property has been implemennted.how do we know whether its of I or of J? the code is showing no compilation error.
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
VulpesRank #55 · 29.2K reputationPosted Mar 29, 2012, 6:07 AM EDT
✓ Accepted answer0
If a class C implements two interfaces, if1 and if2, each of which have a property w with the same signature, then C.w is considered to implement both if1.w and if2.w as the following example makes clear:
using System;
interface if1
{
int w {get; set;}
}
interface if2
{
int w {get; set;}
}
class C : if1, if2
{
public int w {get; set;}
}
class Test
{
static void Main()
{
C c = new C();
if1 I = c;
I.w = 3;
Console.WriteLine(c.w); // 3
if2 J = c;
J.w = 4;
Console.WriteLine(c.w); // 4
Console.ReadKey();
}
}
Even though we've set w using interface references, we can still access it in both cases through a C reference.
However, if you want each interface to have separate implementations of w within C, then you need to use explicit interface implementation. Each implementation of w can then only be accessed via an interface reference of the appropriate type, as the following revised example shows:
using System;
interface if1
{
int w {get; set;}
}
interface if2
{
int w {get; set;}
}
class C : if1, if2
{
int if1.w {get; set;}
int if2.w {get; set;}
}
class Test
{
static void Main()
{
C c = new C();
if1 I = c;
I.w = 3;
Console.WriteLine(I.w); // 3
if2 J = c;
J.w = 4;
Console.WriteLine(J.w); // 4
Console.ReadKey();
}
}
If you tried to use c.W, instead of I.w or J.w, then you'd get a compiler error.
VulpesRank #55 · 29.2K reputationPosted Mar 29, 2012, 6:07 AM EDT
Even though we've set w using interface references, we can still access it in both cases through a C reference.
However, if you want each interface to have separate implementations of w within C, then you need to use explicit interface implementation. Each implementation of w can then only be accessed via an interface reference of the appropriate type, as the following revised example shows:
If you tried to use c.W, instead of I.w or J.w, then you'd get a compiler error.
nishant kumar4 reputationPosted Mar 30, 2012, 1:06 AM EDT
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts