locked
Problem with 'IsAssignableFrom' in VB RRS feed

  • Question

  • if (typeof(IComparable<T>).IsAssignableFrom(typeof(T))) { comparer = Comparer<T>.Default; }

    The above code is C# for comparing if a type is assignable from another type. I want to use it in my VB.net app (it's part of a class, the rest of which I have converted to VB).

    The following is the code a code converter created from the above C# code, and it seems correct to me, however it's not allowed, and gives an error that IsAssignableFrom is not a member of System.Type (presumably not implemented in WinRT?).

      If GetType(IComparable(Of T)).IsAssignableFrom(GetType(T)) Then
               comparer = comparer(Of T).[Default]
        End If

    Can anyone supply the correct code for this (specifically the top line that compares the types)?


    I'm a self-taught noob amateur. Please take this into account when responding to my posts or when taking advice from me.

    Tuesday, September 3, 2013 11:24 AM

All replies

  • Does the below approach work?

    Imports System.Reflection
    
            If GetType(IComparable(Of T)).GetTypeInfo().IsAssignableFrom(GetType(T).GetTypeInfo()) Then
                comparer = Comparer(Of T).[Default]
            End If


    Windows Store Developer Solutions #WSDevSol || Want more solutions? See our blog, http://aka.ms/t4vuvz

    Wednesday, September 4, 2013 12:10 AM
    Moderator
  • Does the below approach work?

    Imports System.Reflection
    
            If GetType(IComparable(Of T)).GetTypeInfo().IsAssignableFrom(GetType(T).GetTypeInfo()) Then
                comparer = Comparer(Of T).[Default]
            End If


    Windows Store Developer Solutions #WSDevSol || Want more solutions? See our blog, http://aka.ms/t4vuvz

    Progress! The first line "If..." seems to be correct, thanks!

    But there is still a problem with the second line:

     Dim comparerx As IComparer(Of T) = Me.m_comparer
            If comparerx Is Nothing Then
                If GetType(IComparable(Of T)).GetTypeInfo().IsAssignableFrom(GetType(T).GetTypeInfo()) Then
                    comparerx = Comparer(Of T).[Default]
    
                End If
    
    
     Public Property Comparer() As IComparer(Of T)
            Get
                Return Me.m_comparer
            End Get
            Set(value As IComparer(Of T))
                Me.m_comparer = value
            End Set
        End Property
    

    Now I just get an error on:

    comparerx = Comparer(Of T).[Default]

    (Comparer has no type parameters).

    Removing the parameter doesn't help. What is the correct syntax here?

    The C# code being converted is:

     comparer = Comparer<T>.Default;

    Any ideas?


    I'm a self-taught noob amateur. Please take this into account when responding to my posts or when taking advice from me.

    Wednesday, September 4, 2013 10:09 AM