Search code examples
.netdynamic

Dynamic object allocation and property access


I am developing one wcf client application. here i have 7 different requests.

is there any way to do like below demo code?

T obj =new anyobject ;

obj=DeSeriableXMLToObject<typeof(obj)>(string);

if(obj.property1=="200")
{
}

My deserialise function as below:

public static T DeSeriableXMLToObject<T>(string xml)
{
// process for derisialising
}

i think , we can do this by dynamic in dot net. but i am new to this dynamic concept . could anyone help me out?


Solution

  • i have solved my problem like below.

    dynamic obj= new anyobject();
    
    obj=DeSeriableXMLToObject(xml,obj);
    
    if(obj.property1==200)
    {
    }
    

    my deserialise function as like this;

    dynamic DeSeriableXMLToObject(string xml,dynamic obj1) { 
    //
    Byte[] _bytes = (new UTF8Encoding()).GetBytes(xml);
    
    DataContractSerializer datacontractser = new DataContractSerializer(obj.GetType ());
    
            object deserialized = _datacontractser .ReadObject(new MemoryStream(_bytes));
    
            return deserialized;
    }