locked
extending a class and conversion RRS feed

  • Question

  • User1941854764 posted

    Public Class Person
    Property FirstName as String
    Property LastName as string
    End Class
    'student is a person but we add Grade as property
    Public Class Student
       Inherits Person
    Property Grade as String
    End Class
    There is a function that loads persons from the database.
    dim lstPersons as List Of(Person) = getListOfPersons()
    I have a function defined in Student namespace/class, these objects are different.
    function LoopThroughStudents(lstStudents as List Of(Student))
    '''''
    looping
    '''''
    end function
    To this last function instead of lstStudents I want to pass lstPersons. Is anyway lstPersons can be converted into List Of (Students) and keep the value of the persons ?

    Public Class Person
    	Property FirstName as String
    	Property LastName as string
    End Class
    
    
    'student is a person but we have added Grade as property
    Public Class Student
       Inherits Person
    	Property Grade as String
    End Class

    There is a function that loads persons from the database.

    dim lstPersons as List Of(Person) = getListOfPersons()

    I have a function defined in Student namespace/class, these objects are different.

    function LoopThroughStudents(lstStudents as List Of(Student))
    '''''
    	looping
    '''''
    end function


    To this last function instead of lstStudents I want to pass lstPersons. Is anyway lstPersons can be converted into List Of (Students) and keep the value of the persons ?

    How can I LoopThroughStudents(lstPersons) ????
     

    Monday, August 30, 2010 3:14 PM

Answers

  • User197322208 posted

    In .NET 4, this is called covariance. Replace your List< with IEnumerable<

    http://msdn.microsoft.com/en-us/library/9eekhta0.aspx  ( see the out syntax)

    If you do not have .NET 4, your solution is to create a class

    Public Class Student  

       Inherits List Of  Student

    Public Function TRansformToPerson as List Of  Person

    dim lp as new  List Of  Person

    for each item as Student in Me

    lp.Add Student

    next item

    End Function

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 30, 2010 11:39 PM