Home > OS >  How can i have an if statement when creating an object in c#?
How can i have an if statement when creating an object in c#?

Time:07-16

I want something like this when creating an object,

            var modelObj = new TestModel
            {
                Id = id,
                Description = obj.Description,
                if (status == 1)
                {
                   Service = obj.Url,
                   Username = obj.ServiceUsername,
                }
                else
                {
                  Password = obj.Password,
                  Token = obj.Token,
                  FirstName = obj.FirstName
                }
            }

Is this possible to do with the if statement in c# ?

CodePudding user response:

Is this possible to do with the if statement in c# ?

You can do the same thing with expressions using the conditional operator.

    var modelObj = new TestModel
    {
        Id = id,
        Description = obj.Description,
        Service = status == 1 ? obj.Url : null,
        Username = status == 1 ? obj.ServiceUsername : null,
        Password = status != 1 ? obj.Password : null,
        Token = status != 1 ? obj.Token : null,
        FirstName = status != 1 ? obj.FirstName : null,

    };

CodePudding user response:

You can just do this afterwards if this is an object data assignment.

    var modelObj = new TestModel
    {
        Id = id,
        Description = obj.Description            
    }

    if (status == 1)
    {
       modelObj.Service = obj.Url,
       modelObj.Username = obj.ServiceUsername,
    }
    else
    {
      modelObj.Password = obj.Password,
      modelObj.Token = obj.Token,
      modelObj.FirstName = obj.FirstName
    }

Otherwise best bet is to use a class constructor instead of inline initialization.

CodePudding user response:

If I suggest proper way to do it then.

  1. Create method something like this.
    // Here you can use specific type instead of dynamic but your code miss that.
    public TestModel GetTestModel(int status, int id, dynamic obj)
    {
        if (status == 1)
        {
            return new TestModel()
                {
                    Id = id,
                    Description = obj.Description,
                    Service = obj.Url,
                    Username = obj.ServiceUsername,
                };
        }
        else
        {
            return new TestModel()
                {
                    Id = id,
                    Description = obj.Description,
                    Password = obj.Password,
                    Token = obj.Token,
                    FirstName = obj.FirstName
                };
        }
    }

  •  Tags:  
  • c#
  • Related