c# - What should an "out" parameter be in case of failure? -


i have read related question: what should out value set unsuccessfull tryxx() method?

however question deals primitive types such integers etc.

i implementing similar tryxxx, answers on question default value of out should null when method unsuccessful. out type in method non-nullable value type.

take example code:

    public bool tryparsefileline(string fileline, out fileresult result)     {         if(!string.isnullorwhitespace(fileline))         {             result = null;             return false;         }         // logic here if string wasn't empty etc.     }      public struct fileresult     {         public bool isvalid;         public string value;     } 

the result = null line not compile because cannot convert null 'fileresult' because non-nullable value type.

so in situation, should value of result when method fails? ideally null because makes sense me.

edit: using nullable<fileresult> idea here? example:

        public bool tryparsefileline(string fileline, out nullable<fileresult> result)     {         if(!string.isnullorwhitespace(fileline))         {             result = null;             return false;         }         // logic here if string wasn't empty etc.         result = new fileresult();     } 

as rule of thumb, either use default(filestruct) (and make sure value makes sort of sense - it's equivalent of new filestruct() value types), or better yet, scratch out parameter altogether , return nullable filestruct? value.

public fileresult? tryparsefileline(string fileline) {     if (string.isnullorwhitespace(fileline))         return null;      ... } 

the bool trysomething(out result result) pattern predates nullable structs in langugage, , imho shouldn't used new code makes inconventient caller (because of need declare additional variable of time).
using nullable struct return value nicer caller, , doesn't require return meaningless values in code.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -