Home > Software design >  I want to initialize an Object (UserModel ) to empty object instead of a null
I want to initialize an Object (UserModel ) to empty object instead of a null

Time:05-04

I want to initialize an Object UserModel to empty instead of null.

Reason am asking my question is that i want to get rid of the following piece of code:

user = new UserModel { ISOCode= "ZAF", Gender = Gender.Male }

I don't want to new it up inside the if statement, I just want to assign to the empty object.

UserModel user = null;

string mAge = Person.PersonContext.FirstOrDefault(x => x.Gender.ToLower() == "male");

string fAge = Person.PersonContext.FirstOrDefault(x => x.Gender.ToLower() == "female");

if (!string.IsNullOrEmpty(mAge))
{
 user = new UserModel { ISOCode= "ZAF", Gender = Gender.Male }
}
 else if (!string.IsNullOrEmpty(fAge))
{
 user = new UserModel { ISOCode = "USA",  Gender = Gender.Female} 
}

CodePudding user response:

You can do it using new keyword,

UserModel user = new UserModel();  //Initialize with default constructor
string mAge = "";
string fAge= "";


if (!string.IsNullOrEmpty(mAge))
  user.Gender = Gender.Male;
else if (!string.IsNullOrEmpty(fAge))
  user.Gender = Gender.Female;

CodePudding user response:

How about using a nested conditional operator?

var user = new UserModel 
{ 
    Gender = 
        !string.IsNullOrEmpty(mAge) ? Gender.Male : 
        !string.IsNullOrEmpty(fAge) ? Gender.Female : null 
};

I've assumed the Gender member of your UserModel is nullable.
If it is not then you should replace null with some fallback value, like Gender.Unknown

  • Related