C # Return value of a property that is null

Possible duplicate:
Enter the result using the Ternary operator in C #

I came across this script and there seems to be no natural way to return a nullable int. The code below gives a compilation error because the ternary operator does not like zero.

public int? userId
{
    get
    {
        int rv;
        return int.TryParse(userIdString, out rv) ? rv : null;
    }
}

So, you (or just me) really need to go all the way and conjure all of this:

public int? userId
{
    get
    {
        int id;
        if(int.TryParse(userIdString, out id)){
           return id;
        }
        return null;
    }
}

EDIT: Is there a more natural way to create a nullable instance to make the ternary operator work?

+3
source share
4 answers
public int? userId 
{ 
    get 
    { 
        int rv; 
        return int.TryParse(userIdString, out rv) ? (int?)rv : null; 
    } 
} 
+10
source
public int? userId
{
    get
    {
        int rv;
        return int.TryParse(userIdString, out rv) ? (int?)rv : null;
    }
}
+4
source

: ; , - , ... , . null , ; int - , , null . int? int int? , null int?.

, :

public int? userId 
{ 
    get 
    { 
        int rv; 
        return int.TryParse(userIdString, out rv) ? rv : (int?) null; 
    } 
}

, ; int?. int rv .

, :

return int.TryParse(userIdString, out rv) ? rv : new int?(); 

return int.TryParse(userIdString, out rv) ? rv : default(int?); 

, "casted null" - , .

:

public static class Null
{
    public static T? For<T>() where T : struct
    {
        return default(T?);
    }
}

:

return int.TryParse(userIdString, out rv) ? rv : Null.For<int>(); 

, , :)

+3

int (non-nullable) null . int? .

+1

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


All Articles