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?
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
.
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 };
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.