Q:
What's wrong with the below generic class?
VB.NET
Imports
System.Data
Imports
System.Web
Public
Class
GenericClass(
Of
T
As
DataTable)
Public
Function
GetValue(
ByVal
val
As
T)
As
T
Return
val
End
Function
Public
Function
GetValue(
ByVal
val
As
T)
As
DataTable
Return
val
End
Function
Public
Sub
GetValue(
ByVal
val
As
T)
HttpContext.Current.Response.Write(val)
End
Sub
End
Class
C#
using
System.Data;
using
System.Web;
public
class
GenericClass
where
T :
DataTable
{
public
T GetValue(T val)
{
return
val;
}
public
DataTable
GetValue(T val)
{
return
val;
}
public
void
GetValue(T val)
{
HttpContext
.Current.Response.Write(val);
}
}
A:
At first glance, the overloaded methods appear to be unique. However, this is not the case. In VB.NET, the first 2 methods would error and in C# the last 2 methods would error. Why does this happen? Like non-generic methods, your generic methods must be unique by their method signatures, not just by their return types.
I love mysteries. However, this one is pretty simple.
Q:
What is wrong with the following generic type?
VB.NET
Public Class
BaseClass(
Of
K, V)
End Class
Public Class
SubClass1
Inherits
BaseClass(
Of
K, V)
End Class
Public Class
SubClass2
Inherits
BaseClass(
Of Integer
,
Long
)
End Class
C#
public class
BaseClass
{ }
public class
SubClass1
:
BaseClass
{ }
public class
SubClass2
:
BaseClass
<
int
,
long
> { }
A:
If you were to compile the above code, the compiler would generate an error for SubClass1. SubClass1 is an open type and generates no point of reference for types K and V. SubClass2 is a constructed type and, since it has type arguments declared, will compile.