5

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?

3 Answers 3

9

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)))
{
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

4

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;
}

Comments

2

You could return default(K).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.