tags:

views:

73

answers:

3

Lets say you have a generic function called "SafeToString". The purpose is to be able to pass anything in and always get back a sane response without any exceptions. How would you want it to respond to these inputs?

  • Null -> Null or String.Empty
  • DBNull.Value -> Null, String.Empty, or some text like ""
  • Nullable containing a null -> Null, String.Empty, or some text like ""
  • FSharpOption containing None -> Null, String.Empty, or "None"
  • FSharpOption containing Some(5)-> "5" or "Some(5)"
A: 

It is possible to implement such function using extension method. Extension methods work fine with null input parameters.

And yes, I agree that NullReferenceException caused by ToString is very annoying in logging functionality.

Vitaliy Liptchinsky
Oh yes, of course it would be an extension method. The question is more about what would *you* like to see if you were to use it.
Jonathan Allen
+1  A: 

I think it's important to be able to distinguish among different sorts of null/empty values. So I'd favor something like:

  • null -> "null"
  • DBNull.Value -> "DBNull", or maybe "DBNull.Value" if you value the ability to distinguish the value from the name of the class
  • Nullable containing null -> "null <typename>". Nullables differ from normal nulls in that they have a type associated with them, and it's potentially useful to know about.
  • FSharpOption None -> "None"
  • FSharpOption Some(5) -> "Some(5)", just as F# usually does, special thanks to Grauenwolf for checking on this.
David Seiler
If you were to use this to populat a GUI or printed report, whould you still want to it that way?
Jonathan Allen
Don't null references also have a type associated with them? Consider: `string s = null;` `Type t = typeof(s);`
Steven Sudit
I double checked, FSharpOption.ToString in beta 2 will use "Some(5)"
Jonathan Allen
@Steven, you would lose that information when you pass it to a function.
Jonathan Allen
@Grauenwolf: If I passed the null string to a function that took an object, then yes. However, that would be the case if I passed an `int?` that was null. I guess, more generally, if I pass a null child reference to a method that took the base class reference, it would not be able to distinguish that from passing a null base reference. Then again, I don't know that we'd even want it to.
Steven Sudit
+3  A: 

This is not answering your question, so forgive me. But you an always use Convert.ToString() on objects to avoid getting exceptions. For instance:

string x = null;
string a = x.ToString(); // throws exception

string b = Convert.ToString(x); // this is fine
Dan Diplo