简体   繁体   中英

How to assign a value to a property of an object only if that object is not null in c#

Homework homework = isposted ? new Homework() : null;
If(homework != null) 
{
 homework.Id = 3;
 homework.Name = "Draw an Apple";
}

// Why can't I use like this ?
homework ? .Id = 3;
homework ? .Name = "Draw an Apple"; // instead of checking for if condition

// Is there any way to minimise the code length?`

you can use object initialization to shorten it a fair bit

Homework homework = isposted 
? new Homework
{
    Id = 3,
    Name = "Draw an Apple"
} : null;

Actually, I had an object like Homework homework = isposted ? oldHomework : null;

I would assume you want a copy of the oldHomework , then you can use this code below

Homework homework = isposted 
? new Homework
{
    Id = oldHomework.Id,
    Name = oldHomework.Name
} : null;

You can't assign a value to an object that is NULL. The ? is for reading properties, not setting them.

var x = homework.Id;   // Will throw an error if homework is NULL
var y = homework?.Id;  // Will be NULL if homework is NULL

For setting properties, you definitely want to check for NULL and then only set them if it is not NULL. Just exactly the way you're doing it is perfect.

There is no such operator, the closest way of achieving what you wanted I could think of is by using an extension method like this:

public static class Extensions
{
    public static void IfNotNull<T>(this T obj, Action<T> action)
    {
        if (obj == null)
            return;
        action(obj);
    }
}

Homework homework = isposted ? new Homework() : null;
homework.IfNotNull(h => h.Id = 3);
homework.IfNotNull(h => h.Name = "Draw an Apple");

However the extension method still uses an if statement. It doesn't need to be an extension method.

To be honest I'd never use such solution in a real project. You should not sacrifice code readability just to use fewer lines of code, this solution doesn't even improve performance. I only wanted to share the closest solution I could find for your question.

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