Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object initialization in C#

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 ?

like image 613
Isuru Avatar asked Mar 12 '26 12:03

Isuru


2 Answers

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" }
};
like image 181
Marc Gravell Avatar answered Mar 15 '26 01:03

Marc Gravell


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; }
}
like image 38
Jon Skeet Avatar answered Mar 15 '26 00:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!