Thursday, November 19, 2009

.NET Error: Implementing property must have matching 'Readonly' or 'Writeonly' specifiers

Error Description:

The compiler error Implementing property must have matching 'Readonly' or 'Writeonly' specifiers occurs When implementing property of the interface in the class.


Example:
Interface IComparer 

Public Interface IComparer


#Region "Methods"


Private Function Compare(ByVal x As [Object], ByVal y As [Object]) As
Integer

……

#End Region

End Interface


 

Class Implements the property Compare of IComparer interface:

Public Class DateTimeReverserClass

Implements IComparer

Private Function Compare(ByVal x As [Object], ByVal y As [Object]) As
Integer //=> Error throws here

Dim dx As DateTime = DirectCast(x, DateTime)
Dim dy As DateTime = DirectCast(y, DateTime)
If dx > dy Then
   Return -1
Else
   Return 1
EndIf

End Function

End Class

Reason:
The compiler is not able to find the matching property implementation on interface 'IComparer'
 

Possible Solutions:

The work around is to include the Implements clause to give the fully qualified name of the property (Format: Implements <Interface Name>.<Property Name>)

 

In the above example, replace the line "Private Function Compare(ByVal x As [Object], ByVal y As [Object]) As Integer" with "Private Function Compare(ByVal x As [Object], ByVal y As [Object]) As Integer Implements IComparer.Compare"


 Public Class DateTimeReverserClass

Implements IComparer


Private Function Compare(ByVal x As [Object], ByVal y As [Object]) As
Integer Implements IComparer.Compare

Dim dx As DateTime = DirectCast(x, DateTime)

Dim dy As DateTime = DirectCast(y, DateTime)

If dx > dy Then
Return -1
Else
Return 1

EndIf

End Function

End Class


 

Now the compiler error will not occur.

1 comment:

  1. It's good, but what if the user the function Compare has generated by designer and can't be changed - how I can use a Partial class for give the fully qualified name of the property?

    ReplyDelete