SajjadZare SajjadZare - 7 days ago 5
C# Question

How to copy Data from one class to another

Imagine that i have classes like below

public class A
{
public int a;
public B [] b;
}

public class B
{
public int a;
public int b;
}
-------------------------
public class C
{
public int a;
public D [] b;
}

public class D
{
public int a;
public string b;
}


How to copy data of Class C to A ?
it's simple but because of list (B[] , D[]), i don't know?

Answer

To keep it simple and answer your question, here is the code needed. The anticipated issues? I've commented the line I am most skeptical about, I hope you're considering another design because this design somewhat resembles a recipe for disaster.

This answer however should set you on the right path, you can implement further null & sanity checks.

public class A
{
    public int a;
    public B[] b;

    public A()
    {

    }
    public A(C c)
    {
        a = c.a;
        b = c.b.Select(p => new B
        {
            a = p.a,
            b = int.Parse(p.b) // What if p.b isn't a valid, parsable integer?
        }).ToArray();
    }
}

public class B
{
    public int a;
    public int b;
}

public class C
{
    public int a;
    public D[] b;
}

public class D
{
    public int a;
    public string b;
}