Home > Software engineering >  Instanciate class A with values from instantiated class B when A and B inherit from same class (C#)
Instanciate class A with values from instantiated class B when A and B inherit from same class (C#)

Time:01-10

Say I have the following

public class A{
    
     public string foo {get;set;}
     public string bar {get;set;}
     public int baz {get;set;}
    
}


public class B:A
{
    public string wuz {get;set;}
}

public class C:A
{

    public int yuh {get;set;}
}

If I then make an instance of B

var b = new B(){wuz="wow",foo="hello",bar="wordl",baz=18};

and later on I want to use those values of B in C, then I have to manually write


c = new C(){yuh=20, foo = b.foo, bar = b.bar, baz=b.baz};

isn't there a way to make c take the already instantiated values from B in a dynamic way, and parse them onto C? In this example it is easy to to, but say I have 500 properties then it's not feasible

(I'm fairly new to .NET thus there might be a typo/syntax error in the codeexample above, but I think the problem should be rather clear)

CodePudding user response:

You can add a constructor to C that takes an instance of A (or if you really want to do that B). Would look something like this:

public class C:A
{
    public C() {}
    public C(A other)
    {
        this.foo = other.foo;
        ...
    }
    public int yuh {get;set;}
}

If you also want the same capability in B, you might want to add this kind of constructor to A, and call it from C:

public class A{
    public A(){}
    public A(A other)
    {
        this.foo = other.foo;
        ...
    }

    public string foo {get;set;}
    public string bar {get;set;}
    public int baz {get;set;}
    
}

public class C:A
{
    public C(){}
    public C(A other) : base(other) {}

    public int yuh {get;set;}
}

In either case you can now create a new instance of Clike this:

c = new C(b){ yuh = 20};

CodePudding user response:

Yes you can. You need to write method that will take B instance and sets all properties with reflection.

public C CreateCFromB(B bInstance)
{
   var cInstance = new C();
   foreach (var property in typeof(B).GetProperties())
   {
        var propertyValue = property.GetValue(bInstance, null);
        property.SetValue(cInstance, propertyValue);
   }
   return cInstance;
}

You can take more generalized approach with generic types.

public TWhat CreateFrom<TFrom, TWhat>(TFrom tFromInstance)
    where TWhat : TFrom, new()
{
    var tWhatInstance = new TWhat();
    foreach (var property in typeof(TFrom).GetProperties())
    {
        var propertyValue = property.GetValue(tFromInstance, null);
        property.SetValue(tWhatInstance, propertyValue);
    }
  
    return tWhatInstance;
}
  • Related