Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign values to inner class object

Tags:

c#

oop

I have a class like below

public class HintQuestion
{
    public string QuestionCode { get; set; }
    public string QuestionName { get; set; }
}

and another calss like below

public class User
{
    public User()
    {
        HintQuestion = new HintQuestion();
    }
    public HintQuestion HintQuestion { get; set; }
}

The problem is when I create an instance of User calss and assign values to inner class object it is not working. I am using object initialize

User u=new user{HintQuestion.QuestionCode  ="",...

But when I created constructors it's working fine.

like image 877
शेखर Avatar asked Mar 19 '23 06:03

शेखर


1 Answers

Using an object initializer you have to set the User.HintQuestion property the same way as you do in your constructor, assign a HintQuestion object to it, which you can also create using an initializer:

User u = new User {
    HintQuestion = new HintQuestion { QuestionCode = "", QuestionName = "" }
};
like image 125
famousgarkin Avatar answered Apr 05 '23 05:04

famousgarkin