Zero-coalescing operator & && operator in C #

Is it possible to use the operator ??and the operator &&in any case in the following case:

bool? Any
{
   get
   {
      var any = this.ViewState["any"] as bool?;
      return any.HasValue ? any.Value && this.SomeBool : any;
   }
}

This means the following:

  • if anynull, then this.Any.HasValuereturnfalse
  • if anyit matters, then it returns the value taking into account another logical property, i.e.Any && SomeBool
+3
source share
7 answers

I am wondering why no one has suggested this so far:

bool? any = this.ViewState["any"] as bool?;
return any & this.SomeBool;

It returns

  • nullif anynull, regardless of the value this.SomeBool;
  • trueIf both anyand this.SomeBoolare true; and
  • false, any null, this.SomeBool - false.
+4

null , null, , ?? .

+4

, ?

bool? Any 
{ 
   get 
   { 
      return ((this.ViewState["any"] as bool?) ?? false) && this.SomeBool;
   } 
} 

bool? , bool.

:

class Program
{
    private static readonly Dictionary<string, object> ViewState = new Dictionary<string, object>();
    private static bool SomeBool;

    static void Main(string[] args)
    {
        ViewState["any"] = (bool?)null; SomeBool = true; Console.WriteLine(Any);
        ViewState["any"] = (bool?)false; SomeBool = true; Console.WriteLine(Any);
        ViewState["any"] = (bool?)true; SomeBool = true; Console.WriteLine(Any);
        ViewState["any"] = (bool?)null; SomeBool = false; Console.WriteLine(Any);
        ViewState["any"] = (bool?)false; SomeBool = false; Console.WriteLine(Any);
        ViewState["any"] = (bool?)true; SomeBool = false; Console.WriteLine(Any);
        Console.ReadLine();
    }

    static bool? Any
    {
        get
        {
            return ((ViewState["any"] as bool?) ?? false) && SomeBool;
        }
    }
}

False
False
True
False
False
False

, , null 1 4, . , , ?

+3

, :

return any ?? (any.Value && this.SomeBool) ? true : new Nullable<bool>();

, , , , if:

if ( !any.HasValue )
  return (any.Value && this.SomeBool) ? true : any;
else 
  return any;

- null, true null, ?

+3

Null Coalescing , . , , , .

, , .

bool? any = this.ViewState["any"] as bool?;

if (any == null)
    return null;

return any.Value && this.SomeBool;

- -

Person contact = Mother ?? Father ?? FirstSibling;

+ , :

Person contact = Mother;
if (contact == null)
    contact = Father;
if (contact == null)
    contact = FirstSibling;
+3

, ??? . , , .

+1

, :

return (any ?? false) && this.SomeBool

-1

Source: https://habr.com/ru/post/1743083/


All Articles