My question is shown in this code
I have class like that
public class MainCS { public int A; public int B; public int C; public int D; } public class Sub1 { public int A; public int B; public int C; } public void MethodA(Sub1 model) { MainCS mdata = new MainCS() { A = model.A, B = model.B, C = model.C }; // is there a way to directly cast class Sub1 into MainCS like that mdata = (MainCS) model; }
Class conversion can be done with the help of operator overloading. This allows data of one class type to be assigned to the object of another class type.
Objects can be converted from one type to another, assuming that the types are compatible. Often this is achieved using implicit conversion or explicitly with the cast operator. An alternative to this is the use of the "as" operator.
Gson for converting one class object to another. First convert class A's object to json String and then convert Json string to class B's object. Show activity on this post. Copy the property values of the given source bean into the **target bean.
using Newtonsoft.Json; Class1 obj1 = new Class1(); Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
public class Class1 { public static explicit operator Class2(Class1 obj) { return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj)); } }
Which then allows you to do something like
Class1 obj1 = new Class1(); Class2 obj2 = (Class2)obj1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With