user282807
user282807

Reputation: 925

Copy properties from class A to class B

Using C#, is there a way to copy properies from Class A that were set ( so if i didnt set some property in Class A I dont want that to get copied over) to class B?

example:

class A
{public string Name {get;set;}
public string Age {get;set;}
}

class B
{public string Name {get;set;}
public string Age {get;set;}
}


A a = new A(){name ="bob"}

Now i have B b = new B(){Age = 30}; I need to copy A to B that way Name of B gets set and Age stays the same. Thanks

Upvotes: 0

Views: 662

Answers (2)

Xaqron
Xaqron

Reputation: 30837

http://automapper.codeplex.com/

Upvotes: 3

lesscode
lesscode

Reputation: 6361

Well, you could do something like:

if (b.Name == null) b.Name = a.Name;
if (b.Age == null) b.Age = a.Age;

But this won't work for value types (like Int32). For those, if you control the definition of the type, you could use Nullable<T>.

Upvotes: 0

Related Questions