Search code examples
c#castingclasstype-conversion

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;    
}

Solution

  • What he wants to say is:

    "If you have two classes which share most of the same properties you can cast an object from class a to class b and automatically make the system understand the assignment via the shared property names?"

    Option 1: Use reflection

    Disadvantage : It's gonna slow you down more than you think.

    Option 2: Make one class derive from another, the first one with common properties and other an extension of that.

    Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!

    Let there be:

    class customer
    {
        public string firstname { get; set; }
        public string lastname { get; set; }
        public int age { get; set; }
    }
    class employee
    {
        public string firstname { get; set; }
        public int age { get; set; } 
    }
    

    Now here is an extension for Object type:

    public static T Cast<T>(this Object myobj)
    {
        Type objectType = myobj.GetType();
        Type target = typeof(T);
        var x = Activator.CreateInstance(target, false);
        var z = from source in objectType.GetMembers().ToList()
            where source.MemberType == MemberTypes.Property select source ;
        var d = from source in target.GetMembers().ToList()
            where source.MemberType == MemberTypes.Property select source;
        List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
           .ToList().Contains(memberInfo.Name)).ToList();
        PropertyInfo propertyInfo;
        object value;
        foreach (var memberInfo in members)
        {
            propertyInfo = typeof(T).GetProperty(memberInfo.Name);
            value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);
    
            propertyInfo.SetValue(x,value,null);
        }   
        return (T)x;
    }  
    

    Now you use it like this:

    static void Main(string[] args)
    {
        var cus = new customer();
        cus.firstname = "John";
        cus.age = 3;
        employee emp =  cus.Cast<employee>();
    }
    

    Method cast checks common properties between two objects and does the assignment automatically.