Question

I have the following Person class

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
    public IEnumerable<Person> Children { get; set; }
}

I could initialize it like this:

Person p = new Person() { FirstName = "John", LastName = "Doe" };

But is it possible to reference another property of Person in the object initializer, so I could do for example something like this?

Person p = new Person()
{
    FirstName = "John",
    LastName  = "Doe",
    Children  = GetChildrenByFullName(FullName);
};

EDIT

For the sake of the question, the referenced property doesn't have to be calculated according to other properties, but its value could be set in the constructor.

Thanks

Was it helpful?

Solution

You can't do that:

void Foo()
{ 
  String FullName = "";

  Person p = new Person()
  {
    FirstName = "John",
    LastName  = "Doe",
    Children  = GetChildrenByFullName(FullName); // is this p.FullName 
                                                 // or local variable FullName?
  };
}

OTHER TIPS

No. When inside the object initialiser, you are not inside an instance of the class. In other words, you only have access to the publicy exposed properties that can be set.

Explicitly:

class Person
{
    public readonly string CannotBeAccessed;
    public  string CannotBeAccessed2 {get;}
    public void CannotBeAccessed3() { }

    public string CanBeAccessed;
    public string CanBeAccessed2 { set; }
} 

I think that you may be able to solve your problem by backing your properties with private local variables. e.g.

class Person {
    private string m_FirstName = string.Empty;
    private string m_LastName = string.Empty;

    public string FirstName {
        get { return m_FirstName; }
        set { m_FirstName = value; }
    }

    public string LastName {
        get { return m_LastName; }
        set { m_LastName = value;}
    }

    public string FullName {
         get { return m_FirstName + " " + m_LastName; }
    }

    public IEnumerable<Person> Children { get; set; }
}

Assuming the object initializer sets the properties in the order that you specify them in the initialization code (and it should), the local variables should be accessable (internally by the FullName readonly property).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top