If an interface defines a ReadOnly Property, how can an implementer provide the Setter to this property? - vb.net

Is there a way for implementers of an interface where a ReadOnly property is defined to make it a complete Read/Write Property ?
Imagine I define an interface to provide a ReadOnly Property (i.e., just a getter for a given value) :
Interface SomeInterface
'the interface only say that implementers must provide a value for reading
ReadOnly Property PublicProperty As String
End Interface
This means implementers must commit to providing a value. But I would like a given implementer to also allow setting that value. In my head, this would mean providing the Property's setter as part of the implementation, doing something like this :
Public Property PublicProperty As String Implements SomeInterface.PublicProperty
Get
Return _myProperty
End Get
Set(ByVal value As String)
_myProperty = value
End Set
End Property
but this will not compile as, for the VB compiler, the implementer no longer implements the interface (because it is no longer ReadOnly).
Conceptually, this should work, because, in the end, it just means Implement the getter from the Interface, and add a setter method. For "normal methods", this would be no problem.
Is there some way of doing it, without resorting to "interface hiding" or "home-made" SetProperty() method, and style having the Property behave like a Read/Write property in the implementations ?
Thanks !
--UPDATE--
(I have moved this question to a separate Question)
My question is really : "why can't this be done in VB.NET", when the following is valid in C#.NET?" :
interface IPublicProperty
{
string PublicProperty { get; }
}
with implementation :
public class Implementer:IPublicProperty
{
private string _publicProperty;
public string PublicProperty
{
get
{
return _publicProperty;
}
set
{
_publicProperty = value;
}
}
}

Now supported in Visual Studio 2015.
What's New for Visual Basic
Readonly Interface Properties
You can implement readonly interface properties using a readwrite property. The interface guarantees minimum functionality, and it does not stop an implementing class from allowing the property to be set.

In the end, I ended up with a solution that matches my goal :
users that access via the Interface see at least a getter
users that access the implementation can Read and Write.
I did this "shadowing" the implemented property like this :
'users who access through interface see only the Read accessor
Public ReadOnly Property PublicProperty_SomeInterface As String Implements SomeInterface.PublicProperty
Get
Return _myProperty
End Get
End Property
'users who work with the implementation have Read/Write access
Public Property PublicProperty_SomeInterface As String
Get
Return _myProperty
End Get
Set(ByVal value As String)
_myProperty = value
End Set
End Property
Then, depending on how you use it, you can do :
Dim implementorAsInterface As SomeInterface = New InterfaceImplementor()
logger.Log(implementor.PublicProperty) 'read access is always ok
implementor.PublicProperty = "toto" 'compile error : readOnly access
Dim implementor As InterfaceImplementor = New InterfaceImplementor()
implementor.PublicProperty = "toto" 'write access

There is nothing at a CLI level which prevents this type of implementation and as you've demonstrated it's already supported by C#. The VB.Net language just doesn't support this style of implementation.
Knowing why though is a bit tough since the decision is almost 10 years removed at this point. Very likely it was just an over site at the time interface implementation was designed.

You can't do it as the interface requires that you implement a ReadOnly Property.
Properties don't allow overloading so there is no way to implement a non-ReadOnly and also a ReadOnly.
I would suggest you either implement a Custom Setter or drop the ReadOnly from the Interface.
Without details of why you want to do this it is hard to suggest the best solution

In Visual Basic, when you implement a method or property from an interface, you can change its name and its visibility. You can leverage that capability to handle the case you are asking about. Prior to Visual Studio 2015, I often did this:
Interface:
Public Interface SomeInterface
ReadOnly Property SomeProperty As String
End Interface
Implementing Class:
Public Class SomeClass
Implements SomeInterface
Public Property SomeProperty As String
Private ReadOnly Property SomeProperty_ReadOnly As String Implements SomeInterface.SomeProperty
Get
Return Me.SomeProperty
End Get
End Property
End Class
The result is that SomeProperty is read-only when accessed through SomeInterface, but read-write when accessed through SomeClass:
Dim c As New SomeClass
c.SomeProperty = "hello" 'Write via class OK
Dim s1 = c.SomeProperty 'Read via class OK
Dim i As SomeInterface = c
Dim s2 = i.SomeProperty 'Read via interface OK
i.SomeProperty = "greetings" 'Syntax Error, interface property is read-only

Related

How can I create a generic class that only works for classes that support certain interface?

Class cacheable(Of T As haveTimeStampandMainStringKey)
Public ReadOnly Property Cache As T
Public ReadOnly Property timestamp As Date
Public Shared Function create(cache1 As T) As cacheable(Of T)
Dim a = New cacheable(Of T)
a._Cache = cache1
a._timestamp = Now
Dim key = T.mainkey 'this things fail to compile
Return a
End Function
End Class
Interface haveTimeStampandMainStringKey
ReadOnly Property TimeStamp As DateTime
ReadOnly Property mainKey As String
End Interface
Basically I want class cacheable to work only with classes that support haveTimeStampandMainStringKey
Yet
Dim key = T.mainkey produces an error
Clearly T supports haveTimeStampandMainStringKey interface. So I should be able to access T.mainkey. I can't. Why? What's wrong with the code?
Why?
It doesn't work because T is a type, not an instance. You need to have an instance to refer to mainKey. You probably want either a.Cache.mainKey or cache1.mainKey.
(If you really want something Shared rather than something attached to an instance, unfortunately, there isn't a good way to do it as it's not supported by .NET except through various reflection-based approaches, see various lamentations about the absence of "static interfaces" over the years.)

Swift readonly external, readwrite internal property

In Swift, what is the conventional way to define the common pattern where a property is to be externally readonly, but modifiable internally by the class (and subclasses) that own it.
In Objective-C, there are the following options:
Declare the property as readonly in the interface and use a class extension to access the property internally. This is message-based access, hence it works nicely with KVO, atomicity, etc.
Declare the property as readonly in the interface, but access the backing ivar internally. As the default access for an ivar is protected, this works nicely in a class hierarchy, where subclasses will also be able to modify the value, but the field is otherwise readonly.
In Java the convention is:
Declare a protected field, and implement a public, read-only getter (method).
What is the idiom for Swift?
Given a class property, you can specify a different access level by prefixing the property declaration with the access modifier followed by get or set between parenthesis. For example, a class property with a public getter and a private setter will be declared as:
private(set) public var readonlyProperty: Int
Suggested reading: Getters and Setters
Martin's considerations about accessibility level are still valid - i.e. there's no protected modifier, internal restricts access to the module only, private to the current file only, and public with no restrictions.
Swift 3 notes
2 new access modifiers, fileprivate and open have been added to the language, while private and public have been slightly modified:
open applies to class and class members only: it's used to allow a class to be subclassed or a member to be overridden outside of the module where they are defined. public instead makes the class or the member publicly accessible, but not inheritable or overridable
private now makes a member visible and accessible from the enclosing declaration only, whereas fileprivate to the entire file where it is contained
More details here.
As per #Antonio, we can use a single property to access as the readOnly property value publicly and readWrite privately. Below is my illustration:
class MyClass {
private(set) public var publicReadOnly: Int = 10
//as below, we can modify the value within same class which is private access
func increment() {
publicReadOnly += 1
}
func decrement() {
publicReadOnly -= 1
}
}
let object = MyClass()
print("Initial valule: \(object.publicReadOnly)")
//For below line we get the compile error saying : "Left side of mutating operator isn't mutable: 'publicReadOnly' setter is inaccessible"
//object.publicReadOnly += 1
object.increment()
print("After increment method call: \(object.publicReadOnly)")
object.decrement()
print("After decrement method call: \(object.publicReadOnly)")
And here is the output:
Initial valule: 10
After increment method call: 11
After decrement method call: 10

Auto Property with public getter and private setter

NOTE: This is not a duplicate of VB.NET equivalent of C# property shorthand?. This question is about how to have different access rights on getter and setter of a VB auto-property; e.g public getter and private setter. That question is about the syntax for auto-property (and does not mention this issue).
I am trying to convert an auto Property (public getter and private setter) from C# to VB.NET.
But after conversion VB.NET is maintaining a private field.
C# code
class DemoViewModel
{
DemoViewModel (){ AddCommand = new RelayCommand(); }
public ICommand AddCommand {get;private set;}
}
VB.NET equivalent from code converter is
Class DemoViewModel
Private Sub New()
AddCommand = New RelayCommand()
End Sub
Public Property AddCommand() As ICommand
Get
Return m_AddCommand
End Get
Private Set
m_AddCommand = Value
End Set
End Property
Private m_AddCommand As ICommand
End Class
VB.NET code generates private backing field.
Is it possible to get rid of this back field in source code (like c#)? How?
Without this feature, VB.NET source will have lots of such redundancy.
Using VB.NET, if you want to specify different accessibility for the Get and Set procedure, then you cannot use an auto-implemented property and must instead use standard, or expanded, property syntax.
Read MSDN: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/auto-implemented-properties
If getter and setter have same accessibility, e.g. both are Public, then you can use the auto-property syntax, e.g.:
Public Property Prop2 As String = "Empty"
In VB.NET it's
Public ReadOnly Property Value As String
Then to access the private setter, you use an underscore before your property name
Me._Value = "Fred"
since the answer(s) above hold(s), you may introduce a Public Prop to expose the Private one. This may not be a nice solution but still less code, than expanded Property syntax
Private Property internalprop as object
Public Readonly Property exposedprop as Object = internalprop

VB.NET Interface Property with Getter but no Setter

I wonder how I could do an Interface with Read only property in VB.NET?
In C# I'd do something like:
interface ISomething {
int PropNeeded { get; }
}
But when I try to do the same in VB
Interface ISomething
Property PropNeeded() As Integer
Get
End Get
End Property
End Interface
I got this error message from Visual Studio 2010: "Statement cannot appear within an interface body. End of interface assumed."
Which seems logic, since it's like I tried to give an implementation to the Property... But it's important that the Property has no Setter only a Getter.
Your help would be greatly appreciated!
Readonly Property PropNeeded() As Integer
Interface ISomething
ReadOnly Property PropNeeded() As Integer
End Interface
As a side note, you can use C# to VB online code converters. Telerik code converter

After restricting Setter scope and then applying an interface, scope is disregarded!

If I set a Friend-level scope on a setter, like this...
Public Class MyClass
Public Property IsDirty() As Boolean
Get
Return _isDirty
End Get
Friend Set(ByVal trueFalse As Boolean)
_isDirty = trueFalse
End Set
End Property
End Class
...And then call it from another project, it works correctly. I can't do something like MyClass.IsDirty = True.
Great! That's exactly what I want.
But now if I define an interface, and I will indeed have to do that:
Public Interface IMyClass
Property IsDirty() As Boolean
End Interface
I can do something like:
Dim MyInstance as IMyClass= GetSomeInstanceOfMyClass()
MyInstance.IsDirty=True
...And, bizarrely, it runs! No exceptions are thrown, and the inner variable is set to True. It ignores the Friend scope completely!
That's hideous. What am I missing??
Note: I need this because I'm designing an API, and I want the inner API to be able to set IsDirty, but end-developers shouldn't be able to get into that. Currently I am wrapping the whole class in a facade to get this functionality, but the facade should be unecessary.
Interface methods always have public accessibility. You can't fix that by explicit interface implementation, that will only hide the class method. Simply casting the object to the interface type gives unfettered access again.
EDIT: actually, the problem is easy to solve. Just declare the property ReadOnly in the interface declaration :)
For example:
Public Interface IMyClass
ReadOnly Property IsDirty() As Boolean
End Interface
Public Class Test
Implements IMyClass
Private mIsDirty As Boolean
Private ReadOnly Property IsDirtyImpl() As Boolean Implements IMyClass.IsDirty
Get
Return mIsDirty
End Get
End Property
Public Property IsDirty() As Boolean
Get
Return mIsDirty
End Get
Friend Set(ByVal value As Boolean)
mIsDirty = value
End Set
End Property
End Class
What you are missing is the concept of inplicit and explicit interface implementation. See the answer to this question for more details.
And if you think it's hideous with a Friend setter, try setting it to Private and watch it still be accessible via the interface!