clarify the "return default" usage and what value it returns

Rui Chao 21 Reputation points
2021-06-15T01:36:01.013+00:00

Hi, can someone explains to me what is this "return default" default means? Or where in VS code I can check the value of default? I try to step into the default to see the value, but it cannot be clicked. I also looked at the docs provided from Microsoft (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default)

It provided 3 cases when default is used, I still don't understand this is which case. Below is the code where at the last line is using default:

        try  
        {  
            var json =  
                JsonConvert.DeserializeObject<AEGDeadLetterEvent<AEGGridEvent<AEGEventData<>>>(rawJson);  
            if (json != null)  
            {  
                Logger.Debug($"Successfully parsed AEG DeadLetter grid event as json");  
                return json;  
            }  
            else  
            {  
                Logger.Debug(string.Format("JSON parsed as null"));  
                return default;  
            }  
        }  

Thanks in advance!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,819 questions
0 comments No comments
{count} votes

Accepted answer
  1. WayneAKing 4,921 Reputation points
    2021-06-15T05:11:34.15+00:00

    Since you have C# code, why did you use the forum tag
    for Visual Basic? You should remove that tag and use
    the C# tag instead: dotnet-csharp

    As to default in your code, it appears to be the
    default literal case as described in the docs:

    "Beginning with C# 7.1, you can use the default literal to
    produce the default value of a type when the compiler can
    infer the expression type. The default literal expression
    produces the same value as the default(T) expression where
    T is the inferred type."

    So the line

    return default;

    should return the default value for whatever the return
    type of the method in question has declared/defined.

    • Wayne
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,591 Reputation points
    2021-06-15T06:09:28.33+00:00

    This is the second case.

    It will return the default value of that type according to the return value type, the reference type returns null, the int type returns 0, the bool type returns false, etc.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.