Can one reference a same-named implicit property in an explicit Interface implementation?
-
19-08-2019 - |
Question
Say I have a type that implements a property with a string type:
public class Record
{
public string Value { get; set; }
}
Then I have an interface that defines a property with the same name:
public interface IIntValued
{
public int Value { get; set; }
}
I can use explicit interface as follows:
public class Record : IIntValued
{
public string Value { get; set; }
int IIntValued.Value
{
get{ return 0; } set{}
}
}
However, if I want to be able to reference the string "Value" in my explicit interface, can I do it? If so, how? I imagine it to be something like:
public class Record : IIntValued
{
public string Value { get; set; }
public int IIntValued.Value
{
get
{
string value = /*Magic here*/.Value;
return int.parse(value);
}
set{}
}
}
As you can see, I want the "string valued" "Value" property for an expression in the "int valued" "Value" property. If it were another explicitly implemented interface member, I could typecast to that Interface and then use, but how would it work for an implicit type member?
Note: The example is a bit contrived, but hopefully demonstrates the language question.
Solution
For an implicit type member, just Value
or this.Value
should be fine - because it won't resolve to IIntValued.Value
by default.
OTHER TIPS
Sure you can! The problem is that you were placing accessibility keywords where they are illegal. Explicitly-implemented members can not have an accessibility keyword. An implicitly-implemented would be written with out the IIntValue. prefix to the member name.
Here's a sample that works.
public interface IIntValued
{
int Value { get; set; }
}
public class Record : IIntValued
{
public string Value { get; set; }
int IIntValued.Value
{
get
{
string value = this.Value;
return int.Parse(value);
}
set { }
}
}
Yes, you can access both properties. It depends on the type of the variable used to access the property. Observe:
Record myInstanceAsRecord = myInstance;
IIntValued myInstanceAsIIntValued = myinstance;
string valueAsString = myInstanceAsRecord.Value;
int valueAsInt = myInstanceAsIIntValued.Value;
Ugh, after writing the summary, I realized that I knew the answer. :P
If I take this
and typecast it to the class type, then the explict implementation will not be included:
string value = ((Record)this).Value; //is the implicit string.
Edit: After some further input (Thanks responders!) it was pointed out that there is no need to manually do something that the compiler is doing automatically. Thus:
string value = this.Value;
would have worked. This is, of course, because the this
is not an interface variable, and so the implicit property would be the one selected by default.