Home > Software engineering >  How to check and convert Generic Type
How to check and convert Generic Type

Time:10-19

I have below code but not able to validate the type of displayPage.

using System;

public class Page{}
public class ContentPage: Page{}
public class BaseViewModel{}

public class ChildViewModel : BaseViewModel {}

public class Base<T> : ContentPage where T:BaseViewModel{
    public void Method(){
        Console.WriteLine("in Base=>Method");
    }}
public class ChildPage : Base<ChildViewModel> {}
public class Program{
    public static void Main(){
        Page displayPage = new ChildPage();
        Console.WriteLine(displayPage is Base<BaseViewModel>);
        if(displayPage is Base<BaseViewModal>) **-> Its returning false** {
            (displayPage as Base<BaseViewModel>).Method();
        }}}

CodePudding user response:

You need to pass the type along with Base class name

(displayPage as Base<BaseViewModel>).Method(); 

Pseudo code

using System;
            
public class Page
{
}
public class ContentPage: Page
{
}
public class BaseViewModel
{
}

public class Base<T> : ContentPage where T:BaseViewModel
{
    public void Method()
    {
        Console.WriteLine("in Base=>Method");
    }
}

public class Program
{
    public static void Main()
    {
        Page displayPage = new Base<BaseViewModel>();

        (displayPage as Base<BaseViewModel>).Method();
    }
}

here is fiddle: https://dotnetfiddle.net/hiAPmq

CodePudding user response:

If you are in generic class like FormBase<T>, then you case just :

public class FormBase<T> where T: BaseViewModel
{ 
    public void Display(Page displayPage)
    {
        (displayPage as Base<T>).Method();
    }
}

Else, you need use covariance on the generic type. But it's possible only with delegate and interface. To do this, you need to add a interface like :

using System;

public class Page { }
public class ContentPage : Page { }
public class BaseViewModel { }

public interface IBase<out T> where T : BaseViewModel
{
    void Method();
}

public class Base<T> : ContentPage, IBase<T> where T : BaseViewModel
{
    public void Method()
    {
        Console.WriteLine("in Base=>Method");
    }
}

public class Program
{
    public static void Main()
    {
        Page displayPage = new Base<BaseViewModel>();

        (displayPage as IBase<BaseViewModel>).Method();
    }
}

In the declaration interface interface IBase<out T>, the keyword out enable the covariance for the generic type.

More information in the documentation :

Covariance and contravariance in generics

  • Related