Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force type cast between classes of different namespaces

How Force type cast between classes of different namespaces.

Both namespaces have same class.

like image 810
Shivi Avatar asked Dec 10 '22 09:12

Shivi


2 Answers

You can't cast an object to a type it is not. If it belongs to a different namespace then it is not the same class. You will have to create a converter:

public static Namespace1.SomeClass Convert(Namespace2.SomeClass someClass) {
    Namespace1.SomeClass rtn = new Namespace1.SomeClass();
    rtn.SomeProp = someClass.SomeProp;
    rtn.SomeOtherProp = someClass.SomeOtherProp;
    return rtn;
}

you could even use reflection to set all the properties on Namespace1.SomeClass that have the same name as Namespace2.SomeClass.

Also, if you own the code to one of the classes, you can check into overloading explicit and implicit on your class.

like image 192
Joel Avatar answered Dec 11 '22 23:12

Joel


You can create generic Converter so you don't have to do this each time you need to cast a different type of objects,

T ConvertObject<T>(object M) where T : class
{
    // Serialize the original object to json
   // Desarialize the json object to the new type 
 var obj = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(M));
 return obj;
} 
// Test ObjectToCast is type Namespace1.Class, obj is Namespace2 
 Namespace2.Class obj = ConvertObject<Namespace2.Class>(ObjectToCast);

Assuming that both classes are the same this will work.

like image 42
Munzer Avatar answered Dec 12 '22 00:12

Munzer