Chris Ward
Chris Ward

Reputation: 817

Function to accept nullable type and return nullable type or string

Basically I want to be able to have one function that takes in a Nullable Type and then returns the value if it has one or the string value "NULL" if it's null so the function needs to be able to take in any nullable type and then return that type or return the string NULL. Below is kind of what I'm looking for as an example I just can't seem to figure out what I need to do as far as my function.

UInt16? a = 5;
UInt16? b = null;
UInt32? c = 10;
UInt32? d = null;

Console.WriteLine(MyFunction<UInt16?>(a)) // Writes 5 as UInt16?
Console.WriteLine(MyFunction(UInt16?>(b)) // Writes NULL as String
Console.WriteLine(MyFunction(UInt32?>(c)) // Writes 10 as UInt32?
Console.WriteLine(MyFunction(UInt32?>(d)) // Writes NULL as String

static T MyFunction<T>(T arg)
{
    String strNULL = "NULL";

    if (arg.HasValue)
        return arg;
    else
        return strNULL;
}

Upvotes: 0

Views: 122

Answers (1)

empi
empi

Reputation: 15901

static string MyFunction<T>(Nullable<T> arg) where T : struct
{
    String strNULL = "NULL";

    if (arg.HasValue)
        return arg.Value.ToString();
    else
        return strNULL;
}

Upvotes: 2

Related Questions