1

I have a plain object with some boolean property, something like this:

public class Object
{
    public bool Prop { get; set; }
}

I want to do something like this:

Object obj;
if(obj != null) { obj.Prop = true; }

but due to stylecop rules I cannot have that if all in one line, I have to split it on multiple lines and this is getting less readable to me. I tried obj?.Prop = true but it is giving me an The left-hand side of an assignment cannot contain a null propagating operator error, which I understand. Any other operator I can use? I'm not really expert in c# so I'm not sure which one is the one I should use.

Here is a quick playground to use for testing if you need it: https://ideone.com/LfjKFD

bracco23
  • 2,181
  • 10
  • 28
  • 1
    obj = obj != null ? obj.prop = true : null – AliK Nov 13 '20 at 12:19
  • if it is getting less readable to you, maybe you need to discuss it with your team about it. Cause in *my* opinion your version is less readable, and its really opinion-based debate. – kuskmen Nov 13 '20 at 12:19
  • Why just don't use an [object initializer](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#object-initializers) here? – Pavel Anikhouski Nov 13 '20 at 12:20

3 Answers3

3

You can't do it without if statement. In my opinion the only thing you can do is

if(obj != null) obj.Prop = true;

In this case you can make it in one line but you can't use ternary operator.

Mumtozbekov
  • 104
  • 2
0

?. called also Elvis Operator is usefull only to access safely an object property not to set it.
To set a property you need to be sure that the object is already initialized and for so the simple way is to check against null using an If statment

if(obj!=null) obj.Prop = someValue;

I don't know if, by your question, you try to make it more simple and readable than that ( as far as for me it is the most obvious and intuitive way), but you can use other solution like mentioned in this post

Ismail Diari
  • 498
  • 3
  • 8
0

This is the only way you can reach it and you don't need any line of code to use Prop. Bool Prop is false by default. But since object shoud be created before assigning anything we can use a default constructor to assign Prop.

public class PlainObject
{
      public bool Prop { get; set; }

         public PlainObject()
          {
           Prop=true;
          }

}

but it doesn't have any practical use since if you try to check plainObject.Prop and plainObject is null , you will have a compiller error already. Object is null only wnen it is not created. Why just don't check if (plainObject==null) or use plainObject?. It will be the same. You don't need any extra flag.

Serge
  • 40,935
  • 4
  • 18
  • 45