Question: Basically I want the following generic function:

```
public string StringOrNull<T> (T value)
{
    if (value != null)
    {
       return value.ToString();
    }
    return null;
}

```

I know I could use a constraint such as where T: class, but T can be a primitive type, Nullable<>, or a class. Is there a generic way to do this?

**Edit**

Turns out I jumped the gun. This actually works just fine as this sample shows:

```
    class Program
    {
        static void Main(string[] args)
        {
            int i = 7;
            Nullable<int> n_i = 7;
            Nullable<int> n_i_asNull = null;
            String foo = "foo";
            String bar = null;

            Console.WriteLine(StringOrNull(i));
            Console.WriteLine(StringOrNull(n_i));
            Console.WriteLine(StringOrNull(n_i_asNull));
            Console.WriteLine(StringOrNull(foo));
            Console.WriteLine(StringOrNull(bar));

        }

        static private string StringOrNull<T>(T value)
        {
            if (value != null)
            {
                return value.ToString();
            }
            return null;
        }
    }

```

Answer: 
Here's a fun one:

```
public static class ExtensionFunctions{
    public static string ToStringOrNull( this object target ) {
        return target != null ? target.ToString() : null;
    }
}

```

The cool part? This will work:

```
( (string) null ).ToStringOrNull();

```

So will this:

```
 5.ToStringOrNull();

```

Extension functions are pretty awesome... they even work on null objects!

If you pass a primitive type, it will automatically be [boxed](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx), so you don't need to worry about the `null` comparison. Since boxing occurs automatically, you can even explicitly compare an `int` to `null` without an error, but the result will always be `false` (and you'll probably get a compiler warning telling you so).
You can use [default](http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx) keyword to return the default of T:

```
public string StringOrNull<T> (T value)
{
    .....

    return default(T).ToString();
}

```