'How to check discard custom attribute of method?

There is a function call:

(_, var surname) = Foo(); 

and the function:

(string Name, string Surname) Foo() 
{
    // Does the 'Name' attribute have discard symbol?
    ....
}

Is it possible to know it from runtime?



Solution 1:[1]

C# 7 have underscore character _ called discards to create dummy variables. Discards are equal to unassigned variables. The purpose of this feature is to use this variable when you want to intentionally skip the value by not creating a variable explicitly.

In this example, you just calling the Foo method but as a return value, you intentionally don't need the Name and just use _ to discard it:

static void Main(string[] args)
{
    (_, var surname) = Foo();

    Console.WriteLine(surname);
}
static (string Name, string Surname) Foo()
{
    return ("Uncle", "Bob");
}

Now lets see an ideal situation to use discards variable:

if (DateTime.TryParse("04/16/2022", out _))  
{  
     Console.WriteLine("Date is valid");  
}  
else  
{  
    Console.WriteLine("Date is not valid");  
}  

But if you don't use _ then you should consider the scenario as per below:

if (DateTime.TryParse("04/16/2022", out var result))  
{  
    Console.WriteLine("Date is valid");  
}  
else  
{  
    Console.WriteLine("Date is not valid");  
} 

For more information about _ you can check Discards - C# Fundamentals

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1