I have a partial view which does not have any parameters passed to it and is called by multiple apps.
I however want to change the requirements and pass a nullable int
to it and a null checker, but it fails, I am a bit confused, how do I go about this ?
My confusion lies with this line >> Id ?? null ? user.UserId() ;
heres my code
[HttpGet]
public PartialViewResult GetUserById (int ? Id)
{
var user = new GetAuthenticatedUser() ; /// This is a custom inhouse code that returns the User ID and properties
Id ?? null ? user.UserId() ; // I am trying to test if the Id is null then use the user account, if not user the query string Id value
var userId = _user.GetUserBasedOnId(Id)
}
// In a nutshell what I am trying to achieve is this
if (Id == null )
{
var userId = _user.GetUserBasedOnId(user.UserId)
}
else
{
var userId = _user.GetUserBasedOnId(Id)
}
If I tried
Id = Id ?? null ? user.UserId() ;
I get the error
CS0019 Operator ?? cannot be applied to operants of type int and
CodePudding user response:
Declare the int as nullable by changing
public PartialViewResult GetUserById (int ? Id)
to
public PartialViewResult GetUserById (int? Id)
CodePudding user response:
3 flavors, depending on the language version and the prototype of GetUserBasedOnId
:
// inline coalesce, yields an int value
var userId = _user.GetUserBasedOnId(Id ?? user.UserId());
or
// Change to Id if it is null, retains int? type
Id ??= user.UserId()
var userId = _user.GetUserBasedOnId(Id);
or
// New variable, of type int instead of int?
var id = Id ?? user.UserId()
var userId = _user.GetUserBasedOnId(id);
Eventually, you can replace user
with new GetAuthenticatedUser()
(and get rid of the very first instruction) to avoid unnecessary calls to the method when Id
is not null.
Note:
Id ?? null
is useless, because it will yield the contents of Id (being null or not).