Reputation: 27
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# ?
Upvotes: 0
Views: 1846
Reputation: 17485
If I suggest proper way to do it then.
Here in the question there is no information about type of obj. So I am putting that as markup Obj but that needs to replace with actual type.
// Here you can use specific type instead of dynamic but your code miss that.
public TestModel GetTestModel(int status, int id, Obj 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
};
}
}
Upvotes: 0
Reputation: 117064
Here's a version of dotnetstep's answer (that's I'd be happy if he used, and then I'd delete this answer). I like it as it is really quite clean and easy to read.
public TestModel CreateTestModel(int status, int id, Obj obj) =>
status == 1
? new TestModel()
{
Id = id,
Description = obj.Description,
Service = obj.Url,
Username = obj.ServiceUsername,
}
: new TestModel()
{
Id = id,
Description = obj.Description,
Password = obj.Password,
Token = obj.Token,
FirstName = obj.FirstName
};
Upvotes: 0
Reputation: 4951
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,
};
Upvotes: 6
Reputation: 54
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.
Upvotes: 3