Prev | Current Page 183 | Next

Guy Fouch?©, Trey Nash

"Accelerated VB 2008"

RaiseToN
Return i ^ n
End Function
End Structure
Public Structure ADouble
Implements IPowerable
Public d As Double
Public Sub New(ByVal value As Double)
Me.d = value
End Sub
Public Function RaiseToN(ByVal n As Integer) As Object _
Implements IPowerable.RaiseToN
Return d ^ n
End Function
End Structure
Public Class EntryPoint
Shared Sub main()
Dim i As AnInteger = New AnInteger(2)
Dim d As ADouble = New ADouble(2.1)
Console.WriteLine(i.i & " cubed is " & i.RaiseToN(3))
Console.WriteLine(d.d & " squared is " & d.RaiseToN(2))
End Sub
End Class
When run, the previous code displays the following results:
2 cubed is 8
2.1 squared is 4.41
CHAPTER 6 n INTERFACES 104
In the example, both AnInteger and ADouble implement IPowerable. As IPowerable requires a
RaiseToN() implementation, both classes oblige. Finally, main() features two calls to RaiseToN(),
one for each object instance created.
Beware of Side Effects of Value Types Implementing Interfaces
As you??™ve just seen, structures can implement interfaces. However, structures are value types,
not reference types, so you??™ll incur a boxing penalty if you cast a value type to an interface type
or vice versa. Also, if you modify the value via the interface reference, you??™re modifying the
boxed copy and not the original.


Pages:
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
buchsbaum loans with no credit check Fundusze Emerytalne Biuro księgowe Lublin opony goodyear