Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Call <T> object class

How can I dynamically pass the class? (EDIT) call with name string =(

I want to pass A1 or A2 to the getData function

Any ideas or references to support me?

public class A1{
   public int dataA1 {get;set;}
}

public class A2{
   public int dataA2 {get;set;}
}

Type obj= Type.GetType("A2");;

var example = GetData<obj>();

public void GetData<T>(){
   //process T custom (A1 or A2) T = A2
}
like image 897
SuperError Avatar asked Jan 17 '26 09:01

SuperError


1 Answers

You should declare a base class, ABase (or with a better name) and then use this as the basis for your generic processing:

public class ABase
{
    public int data { get; set; }
}

public class A1 : ABase {
    ... implementation that presumably sets data
}

public class A2 : ABase {
    ... implementation that presumably sets data
}

var example = GetData<ABase>();

public void GetData<T>() where T : ABase {
   // Do something with T which can be A1 or A2 but supports GetData
}

In GetData<T>, you can now guarantee that the data property is accessible on both A1 and A2 because it is declared on the base class ABase.

Alternatively, you could implement an interface that defined the property:

public interface IBase
{
    int data { get; set; }
}

public class A1 : IBase {
    // Implement the interface here
    public int data { get; set; }
}

...

Edit following @AnuViswan Comment

As Any Viswan has pointed out, in your example (and therefore mine), GetData<T> does not return anything, but var example is set to the result of the method.

This is no doubt a typo in your example. I'm guessing that GetData<T> should return an int.

like image 80
Martin Avatar answered Jan 20 '26 23:01

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!