简体   繁体   中英

Check whether the method is returning a value or null and based on that assign the value

I have a scenario where I am assigning value to a class property in the below way.

var appResponse = GetAppResponse();
appResponse.LogoImage = GetAppImage(appId);

The problem here is sometimes GetImage(appId) returns null and in that case I don't want to assign that null value to appResponse.LogoImage, only when GetImage(appId) returns a value then only I want to assign that value.

I can use an If condition to check if GetImage(appId) is returning null or not and then assign the value, but then I will be making 2 calls to the method GetImage() which is not a good approach I feel.

In a single line can I check for null and when it is not null then only assign value to appResponse.LogoImage?

I can use a If condition to check if GetImage(appId) is returning null or not and then assign the value, but then I will be making 2 calls to the method GetImage()

Why would you be calling it twice?

Here's just one call:

var appResponse = GetAppResponse();
var appImage = GetAppImage(appId);
if (appImage != null) {
    appResponse.LogoImage = appImage;
}

You could use the null-coalescing operator : ??

appResponse.LogoImage = GetAppImage(appId) ?? appResponse.LogoImage;

From the docs:

The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM