Overriding properties of child objects in a C# class

  • Thread starter Thread starter Helen
  • Start date Start date
H

Helen

I have a person class with a name object. The name object has several
fields including one called "title". The two classes look something
like this:

public class name {
public string title {
// get set code here
}
}

public class person {
private gender;
private m_name;

public Name name {
get { return m_name; }
set { m_name = value; }
}
}

What I want to do is set the gender automatically when the title
property is set.

I know I could have a title property/setter method in Person that will
easily do this, but I'd prefer not to do this because it makes more
sense if title is a field of name (and then it'd be possible to
accidently set the title through name without it affecting the
gender).

I'm wondering if it's possible for person to override the title
property of name by declaring a property something like this:

public class person {
private gender;
private m_name;

public Name name {
get { return m_name; }
set { m_name = value; }
}

public string name.title {
set {
name.title = title;
// gender setting code here
}
}
}

Thanks :)

Helen
 
Hi helen,

no, you can not do this that way. But what you can do is, to create an
event in your Name class. And in the constructor of Person, or in the
setter of person.name to hook to this event some person's private method
which will set the gender.

public delegate void SetGenderDelegate(string gander);

public class Name
{
public event SetGenderDelegate TitleChange;

public string Title
{
get ...
set
{ //do code
//notify the parent class
if (TitleChange != null)
TitleChange("the gender???");
}
}


public class Person
{
//your declarations

private void TitleChange(string gender)
{
this.gender = gender;
}

public Name name
{
get ...
set
{
//unhook the event from the current instance
this.m_name.TitleChange -= new TitleChangeDelegate(this.TitleChange);

//set the new name object
this.m_name = value;

//hook the event
this.m_name.TitleChange += new TitleChangeDelegate(this.TitleChange);

}
}

}


Or, you can create a parent field and pass to it the person object. Then
in the Name class in the setter of the title to call parent.Gender, or
.... :)

Sunny
 
Sunny said:
Hi helen,

no, you can not do this that way. But what you can do is, to create an
event in your Name class. And in the constructor of Person, or in the
setter of person.name to hook to this event some person's private method
which will set the gender.

Thanks Sunny :)

Helen
 
Back
Top