Return a null value from a common method

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 null or some kind of empty value if no rows are found. What is the correct syntax for this?

+5
generics c #
source share
3 answers

You can return the default value (K), and that means you will return null if K is a reference type, or 0 for int, '\ 0' for char, etc ...

Then you can easily check if this has been returned:

 if (object.Equals(resultValue, default(K))) { //... } 
+9
source share

You should use a generic class constraint for a parameter of type K (since classes — unlike structures — are nullified)

 internal K GetValue<T, K>(T source, string col) where K : class where T : IBaseObject { // ... return null; } 
+4
source share

You can return default(K) .

+2
source share

All Articles