-1

I am getting

Object not set as an instance of object

when setting class type property of a class please help.

Class

public class Profile
{
    public UsersTB UserObj { get; set; }
    public string newPassword { get; set; }
}

Set

Profile prof = new Profile();
prof.UserObj.userID = 123;//Error here
Christos
  • 53,228
  • 8
  • 76
  • 108
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66

1 Answers1

1

You need to create an object of UsersTB and then assign a value to it's userID.

prof.UserObj = new UserObj();
prof.UserObj.userID = 123;

When we create an instance of an object and we don't specify a value for it's properties, these properties take their default values. In this case by instantiating an obejct of type Profile as below:

 Profile prof = new Profile();

The values that you are stored in the backing fields of properties UserObj and newPassword are the corresponding default values for these type of objects, which in this case is in both cases null.

You could make all of the above in one step by using an object initializer:

var profile = new Profile
{
    UserObj = new UserObj
    {
        userID = 123
    }
};
Christos
  • 53,228
  • 8
  • 76
  • 108