Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# { } operator

Tags:

operators

c#

I cannot find it anywhere. Could you tell me what the expression { } means in c# or give me a link to documentation.

Here is example usage which I have found in my project:

Method(IProfileDocument profileDocument)
{
    if(profileDocument.documentId is not { } documentId
    || string.IsNullOrEmpty(documentId))
    { 
       do something...
    }
}
like image 815
Ellbar Avatar asked Sep 21 '26 11:09

Ellbar


2 Answers

{ } when used with is is an empty property pattern.

{ } is basically equivalent to != null

Read https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns#property-pattern

like image 159
Piglet Avatar answered Sep 23 '26 02:09

Piglet


Property Pattern: A property pattern checks that the input value is not null and recursively matches values extracted by the use of accessible properties or fields.

                string s =null;
                if (s is not { } documentId)
                {

                }
                else
                {
                    string mj = documentId;
                }

Declaration Pattern: The declaration_pattern both tests that an expression is of a given type and casts it to that type if the test succeeds. This may introduce a local variable of the given type named by the given identifier, if the designation is a single_variable_designation.

Here first check profileDocument.documentId is null or not. after that if not null then value asign to new a variable documentId.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/patterns#property-pattern

like image 21
MD. RAKIB HASAN Avatar answered Sep 23 '26 01:09

MD. RAKIB HASAN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!