lundi 27 juillet 2020

Dynamic cast in c# in runtime

I have 2 classes as you can see :

  static void Main(string[] args)
    {

        object m = (??????)"salam";
    }


public class A
{
    public string name { set; get; }
    public static implicit operator A(string _name)
    {
        A aa = new A();
        aa.name = _name;
        return aa;
    }
}
public class B
{
    public string family { set; get; }
    public static implicit operator B(string _family)
    {
        B bb = new B();
        bb.family = _family;
        return bb;
    }
}

I need to cast my string in runtime in this line :

object m = (??????)"salam";

Is there any solution to pass my class name as a string to cast my value .for example in runtime I need to cast "salam" to A or maybe B

The static cast is working good like this

 object m = (A)salam";
 object m = (B)"salam";

But I need to cast my string in runtime

Type x=null;
If(condition) 
x can be type of A
else 
x can be type of B

object m = (x)"salam";




Aucun commentaire:

Enregistrer un commentaire