Codehelp
Codehelp

Reputation: 4747

Setting object properties selectively

I have a business object with these properties:

Public class Person
{
  prop int ID {get; set;}
  prop string Name {get; set;}
  prop string Address1 {get; set;}
  prop string Address2 {get; set;}
}

There is this method

Public Void CreateEntity(Person objPerson)
{
 Person newPerson = new Person();
 newPerson.Name = objPerson.Name;
 newPerson.ID = objPerson.ID;
 newPerson.Address1 = objPerson.Address1;
 newPerson.Address2 = objPerson.Address2;

  ...

  // Do some stuff
 }

It basically assigns all the properties of objPerson to newPerson.

Is there a way to assign selective properties to newPerson?

Instead of doing one-to-one, can it be done selectively like doing only

 newPerson.Address1 = objPerson.Address1;
 newPerson.Address2 = objPerson.Address2;

in the method.

I can have an external configuration where the required properties can be defined. So if that config has only Address1 and Address2, newPerson only gets those two assigned.

Can this be done?

Regards.

Upvotes: 0

Views: 61

Answers (3)

Hary
Hary

Reputation: 5818

With the object initializer:

var obj = new Person { ID = 1, Name = "Test" };

Upvotes: 0

daryal
daryal

Reputation: 14919

Add private fields for each of your public properties and use this fields in your public properties, instead of directly using get; set;.

Then write your conditions into setters, and only if the conditions are satisfied change the private related private field.

private int id;

public int ID {
get
{
    return id;
} 
set
{
    if(someCondition)
       id = value;
} 

}

Upvotes: 0

gdoron
gdoron

Reputation: 150253

If I understood what you want correctly, you can use Object Initializers:

var person = new Person{ ID = 123456, Name = "Foo"};

Object and Collection Initializers (C# Programming Guide)

Upvotes: 1

Related Questions