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?
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
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. .
Yes, you can define a generic method in a non-generic class in Java.
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.
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)))
{
//...
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With