julian bechtold
julian bechtold

Reputation: 2251

how to create Nullable<T> within function?

I have a generic class for an array operation.

I have a function which should return T if a condition is met but return null if the condition is not met.

Minnimal reproducible example:

internal Nullable<T> AppendPoint(T input)
{
    Nullable<T> result = null; // Type T must be a non nullable value type...
    if (Length == Array.Length)
    {
        // result = Array[TailIndex];
    }
    //
    // add new element to array logic here
    //
    return result; //no compiler error
    return null; // works
}

Specifically, this function should insert a value into a circular array. This may Overwrite a previous value which should be returned, if it is beeing overwritten.

Apparently, I can return null, I can create the function with Nullable but I cant create a Nullable within the function.

Upvotes: 0

Views: 175

Answers (1)

Bernard MULLER
Bernard MULLER

Reputation: 143

You need to add a constrain on you generic type T, to tell the compiler T can't be a nullable type. Otherwise, Nullable<T> is not an acceptable expression for the compiler.

internal Nullable<T> AppendPoint(T input) where T : struct

Upvotes: 1

Related Questions