Nullable type to string function

written by Ryan Olshan on Monday, February 13 2006

I just answered a thread where somebody wanted to know how to take any nullable type, check if it's value is null, and depending on that either return String.Empty or ToString. Here's how you do that:

    public static string ConvertNullableToString<T>(T? value) where T : struct

    {

        return value.ToString() ?? String.Empty;

    }

 

    int? value1 = null;

    int? value2 = 9;

 

    string stringValue1 = ConvertNullableToString<int>(value1);

    string stringValue2 = ConvertNullableToString<int>(value2);

Kick this post on .NET Kicks

Similar Posts

  1. Nullable Types
  2. Inheritence with Generics
  3. Generic ExecuteScalar method

Comments

  • XIII on on 2.14.2006 at 10:29 AM

    XIII avatar

    Hi,



    you could also do it like



    return value ?? string.Empty;



    Grz, Kris.

  • Ryan Olshan on on 2.14.2006 at 7:55 PM

    Ryan Olshan avatar

    Ah. Yes. The ?? operator escaped my head when I was creating the code. I just updated it with the ?? operator. Thanks.

Post a comment