You are creating a class named Age.

You are creating a class named Age.
You need to ensure that the Age class is written such that collections of Age objects can be
sorted. Which code segment should you use?

A. Public Class Age
    Public Value As Integer
  Public Function CompareTo(ByVal obj As Object) As Object
    If TypeOf obj Is Age Then
    Dim _age As Age = CType(obj, Age)
    Return Value.CompareTo(obj)
    End If
    Throw New ArgumentException("object not an Age")
    End FunctionEnd Class

B. Public Class Age
    Public Value As Integer
    Public Function CompareTo(ByVal iValue As Integer) As Object
    Try
    Return Value.CompareTo(iValue)
    Catch
    Throw New ArgumentException ("object not an Age")
    End Try
    End FunctionEnd Class

C. Public Class Age
    Implements IComparable
    Public Value As Integer
    Public Function CompareTo(ByVal obj As Object) As Integer _
    Implements IComparable.CompareTo
    If TypeOf obj Is Age Then
    Dim _age As Age = CType(obj, Age)
    Return Value.CompareTo(_age.Value)
    End If
    Throw New ArgumentException("object not an Age")
    End FunctionEnd Class

D. Public Class Age
    Implements IComparable
    Public Value As Integer
    Public Function CompareTo(ByVal obj As Object) As Integer _
    Implements IComparable.CompareTo
    Try
    Return Value.CompareTo((CType(obj, Age)).Value)
    Catch
    Return -1
    End Try
    End FunctionEnd Class


Answer: C 


No comments:

Post a Comment