-1

I have the following classes that I am trying to assign values to but keep getting an Object reference not set to an instance of an object error.

  public class User
{
    public string Gender { get; set; }
    public int Height { get; set; }
    public string UserID { get; set; }
    public Dress dress { get; set; }
}

public class Dress
{
    public int[,] waist { get; set; }
    public int[,] hips { get; set; }
    public int[,] chest { get; set; }
}

I tried doing:

    User user = new User();
    user.UserID = "name";
    user.Gender = "f";
    user.Height = 180;
    user.dress.waist = new int[1, 1];
    user.dress.hips = new int[1, 1];
    user.dress.chest = new int[1, 1];

I thought I was creating the array's wrong but even if I set user.dress.waist to a string I get the same error. All I need to do at the moment is assign values to User's properties and write them out.

Any guidance is greatly appreciated.

Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40
Anthony Ryan
  • 365
  • 2
  • 6
  • 19

3 Answers3

1

You can skip the need to create the sub class by simply using new.

this will work:

public class User
{
public string Gender;
public int[,] Height;
public int[,] UserID;
public Dress Dress = new Dress();
}

public class Dress
{
public int[,] waist;
public int[,] hips;
public int[,] chest;
}

Then:

User.dress.waist = new int[1, 1];
Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51
0

Create a constructor in the User class to instantiate the Dress property since by default, the Dress property is null. Then maybe, you'll also add a new constructor for the Dress class to instantiate its properties so that you can add values to them.

0

I think you need something like this.

User user = new User();
user.dress = new Dress();  //just do this to avoid that error.
user.UserID = "name";
user.Gender = "f";
user.Height = 180;
user.dress.waist = new int[1, 1];
user.dress.hips = new int[1, 1];
user.dress.chest = new int[1, 1];

I believe you may be new to C#. There was a time when I used to assume that when I create an instance of a class, it will automatically instance all the classes that are inside the main.

Unfortunately, that is not true. I am sure there are more elegant ways of making this happen, but I have given you one simple method to solve your issue.

Jay
  • 2,648
  • 4
  • 29
  • 58