When i have declaration like:
class Professor
{
string profid;
public string ProfessorID
{
get { return profid;}
set { profid=value;}
}
student st;
}
class student
{
string name;
string id;
public string Name
{
get { return name;}
set { name=value; }
}
public string StudentID
{
get { return id;}
set { id=value; }
}
}
public void GetDetails()
{
Professor prf=new Professor(){ ProfessorID=1, how to initialize student here?};
}
Inside GetDetails() how can i initialize student ?
First make it accessible:
public student Student { get; set; }
then something like:
Professor prf = new Professor()
{
ProfessorID = "abc",
Student = new student { Name = "Marc", StudentID = "def" }
};
Note that if the property is get-only:
private readonly student _student = new student();
public student Student { get { return _student; }}
Then you can use the alternative syntax (which sets properties without attempting to change the student reference):
Professor prf = new Professor()
{
ProfessorID = "abc",
Student = { Name = "Marc", StudentID = "def" }
};
Your Professor class will need a property setter for the student, at which point you can write:
public void GetDetails()
{
Professor prf = new Professor {
ProfessorID = "1",
Student = new Student { Name = "Jon", StudentID = "1" }
};
}
Without that property, nothing in the Professor class will set the st variable at all.
Note that because in both cases we're only using the parameterless constructor, I've removed the explicit () from the object initializer.
Further note: automatically implemented properties can make your code a lot shorter:
class Professor
{
public string ProfessorID { get; set; }
public Student Student { get; set; }
}
class Student
{
public string Name { get; set; }
public string StudentID { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With