Object initialization in C #
When I have a 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 the student?
source to share
First make it available:
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 get-only property:
private readonly student _student = new student();
public student Student { get { return _student; }}
Then you can use an alternative syntax (which sets properties without trying to change the student reference):
Professor prf = new Professor()
{
ProfessorID = "abc",
Student = { Name = "Marc", StudentID = "def" }
};
source to share
Your class Professor
will need a set of student properties, after which you can write:
public void GetDetails()
{
Professor prf = new Professor {
ProfessorID = "1",
Student = new Student { Name = "Jon", StudentID = "1" }
};
}
Without this property, nothing in the class Professor
will set the variable st
at all.
Note that since we are using a parameterless constructor in both cases, I removed the explicit one ()
from the object initializer.
Next, note that auto-implemented properties can make your code much 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; }
}
source to share
You must make the property Student in Professor:
class Professor
{
string profid;
public string ProfessorID
{
get { return profid; }
set { profid = value; }
}
student st;
public student Student { // New property
get { return st; }
set { st = value; }
}
}
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", Student = new student()};
}
source to share
You need an accessor for your student within a professor
class Professor
{
string profid;
public string ProfessorID
{
get { return profid;}
set { profid=value;}
}
public Student {
get { return st;}
set { st=value;}
}
student st;
}
public void GetDetails()
{
Student s = new Student();
s.StudentId = someId;
s.name = someName;
Professor prf = new Professor { ProfessorID=1, Student = s;};
}
However, your current model is 1 Prof: 1 Student, are you sure this is what you want?
source to share