[RESOLVED] Multiple Interface Variants
That subject line sucks, but I couldn't think of a good one, as the question is a bit odd.
In VB, you can do this:
Code:
Interface ITestReadOnly
ReadOnly Property MyProperty As Boolean
End Interface
Interface ITestRW
Inherits ITestReadOnly
Overloads Property MyProperty As Boolean
End Interface
What this does is allow you to create a class like so:
Code:
Public Class TestClass
Implements ITestRW
Implements ITestReadOnly
Public Property MyProperty As Boolean Implements ITestRW.MyProperty, ITestReadOnly.MyProperty
Get
End Get
Set(value As Boolean)
End Set
End Property
End Class
If an instance of TestClass is created and put in a variable of type ITestRW, then the property is read/write, whereas if the class is put in a variable of type ITestReadOnly, then the property is read only. I'm looking for an efficient way to do the same in C#, and my experience with C# is not up to it. I can see a bad way to do it, but without the Implements keyword, I don't see a way that is as easy. Maybe that's just how it is, but I figured I'd ask on here to see if there is a piece of the language that I am not familiar with that would allow this. The goal is a single property that is read only for one interface and read/write for a second interface, such that one interface could inherit the other to add write functionality where the base interface is read only.
Re: Multiple Interface Variants
C# supports explicit implementation of interfaces, which means that the members of that interface are not accessible via a reference of the class type but only a reference of the interface type. As an example, DataTable explicitly implements IListSource so you can only access its GetList method by casting a reference as type IListSource. You can use explicit implementation in this case like so:
csharp Code:
public interface ITestReadOnly
{
bool MyProperty { get; }
}
public interface ITestReadWrite : ITestReadOnly
{
new bool MyProperty { get; set; }
}
public class Test : ITestReadOnly, ITestReadWrite
{
public bool MyProperty { get; set; }
bool ITestReadOnly.MyProperty => MyProperty;
}
Now, if you have a reference of type Test or ITestReadWrite, you will see the read/write property but, if you cast as type ITestReadOnly, you'll see the read-only property. Not quite as slick as the VB syntax but not especially verbose.
Note also that you need to use new in the derived interface to avoid a warning. That's equivalent to Shadows in VB. There is no explicit directive to overload in C#. It generally happens implicitly but won't in this case because there's no difference in signatures.
Re: Multiple Interface Variants
Thanks, that will do. I felt that I was missing something, because VB did this more neatly, and I didn't want my inexperience with C# keeping me from writing a more compact solution. Still, if this is how it is, I can live with that quite well enough.