Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast class into another class or convert class to another

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;     } 
like image 305
Khalid Omar Avatar asked Sep 08 '10 23:09

Khalid Omar


People also ask

How do you convert from one class to another?

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.

How do I convert a class from one class to another in C#?

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.

How do I convert a class to another class in Java?

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.


1 Answers

Use JSON serialization and deserialization:

using Newtonsoft.Json;  Class1 obj1 = new Class1(); Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1)); 

Or:

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; 
like image 163
Tyler Liu Avatar answered Oct 23 '22 00:10

Tyler Liu