مراد علمدار مراد علمدار - 3 months ago 7
C# Question

C# accessing a property of a generic class T

I need to accessing a property of a generic Class T
I have this method in class geneiric

public T calcuste(T obj)
{
calcaulte testobj= new calcaulte ()
var t = GetValue(obj); // get the type of class for exmple that is calcaulte class

testobj.Id = obj.Id;// thats what I need to do accessing a property of T obj
}

Answer

Try following code.

public T calcuste(T obj)
{
    calcaulte testobj= new calcaulte ();
    calcaulte obj_calcaulte  = obj as calcaulte;
    if(obj_calcaulte  != null)
    {
        testobj.Id = obj_calcaulte  .Id;   
    }

}   

You need to control for null since obj may be null or may belong to different class.