2

there is a similar question here. However my property is not an int or a string but a class itself with many properties of its own. So i want to set the default value to a property of a property.

So here is my example:

public class Claim
{
    public Person Member { get; set; }
    public Person Claimant { get; set; }
}

As you can see my properties arent int's or string's put they are Person's. Each person has many properties and I want to set the default value of one of them for each object.

For example if I make a new person Like this:

Person Pete = new Person { PersonTypeID = 1 };

As you can see Person has a PersonTypeID property. Lets say I want to set that value as 1 for Member and 2 for Claimant as default values every time the Claim class in instantiated. How can I do this?

Community
  • 1
  • 1
6134548
  • 95
  • 1
  • 3
  • 15

2 Answers2

7

Since C#6 you can initialize auto-implemented properties:

public Person Member { get; set; } = new Person { PersonTypeID = 1 }; // or by using the constructor of Person
public Person Claimant { get; set; } = new Person { PersonTypeID = 2 };

otherwise use the constructor of Claim.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Try this in a lazy way

public class Claim
{
    public Person Member { get; set; }
    public Person Claimant { get; set; }

    public Claim()
    {
        this.Member = new Person() { PersonTypeID = 1 };
        this.Claimant = new Person() { PersonTypeID = 2 };
    }
}

or

public class Claim
{
    public Person Member { get; set; }
    public Person Claimant { get; set; }

    public Claim(int MemberTypeID, int ClaimantTypeID)
    {
        this.Member = new Person() { PersonTypeID = MemberTypeID };
        this.Claimant = new Person() { PersonTypeID = ClaimantTypeID };
    }
}
Zay Lau
  • 1,856
  • 1
  • 10
  • 17
  • or the IoC-way: inject `Person` instance in the ctor, or provide a factory-method, or ... –  Aug 29 '16 at 14:22