Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning null value from generic method

Tags:

c#

.net

generics

So i have this method:

    internal K GetValue<T, K>(T source, string col) where T : IBaseObject
    {
        string table = GetObjectTableName(source.GetType());
        DataTable dt = _mbx.Tables[table];
        DataRow[] rows = dt.Select("ID = " + source.ID);
        if (rows.Length == 0) return K;

        return (K) rows[0][col];
    }

I want to be able to return a null, or some kind of empty value, if no rows are found. What's the correct syntax to do this?

like image 843
Jason Miesionczek Avatar asked Jan 17 '09 04:01

Jason Miesionczek


People also ask

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

Can I inherit from generic type C#?

You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. .

Can we have generic function inside non-generic class?

Yes, you can define a generic method in a non-generic class in Java.

What is placeholder in Generics in C#?

Generics were added in C# 2.0. Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types that they store or use. A generic collection class might use a type parameter as a placeholder for the type of objects that it stores.


2 Answers

You could return default(K), and that means you will return null if K is a reference type, or 0 for int, '\0' for char, and so on...

Then you can easily verify if that was returned:

if (object.Equals(resultValue, default(K)))
{
    //...
}
like image 181
Christian C. Salvadó Avatar answered Sep 21 '22 15:09

Christian C. Salvadó


You have to use the class generic constraint on the K type parameter (because classes - as opposed to structs - are nullable)

internal K GetValue<T, K>(T source, string col)
        where K : class
        where T : IBaseObject
{
    // ...
    return null;
}
like image 26
Tamas Czinege Avatar answered Sep 17 '22 15:09

Tamas Czinege