Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# can I write a generic function to return null or the value as a string?

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;
        }
    }
like image 438
grieve Avatar asked Oct 12 '12 14:10

grieve


1 Answers

default Keyword in Generic Code

In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:

Whether T will be a reference type or a value type.

If T is a value type, whether it will be a numeric value or a struct.

like image 61
Kapil Khandelwal Avatar answered Oct 02 '22 12:10

Kapil Khandelwal