I'm converting a bunch of code from VB to C# and I'm running in to an issue with a method. This VB method works great:
Public Function FindItem(ByVal p_propertyName As String, ByVal p_value As Object) As T
Dim index As Int32
index = FindIndex(p_propertyName, p_value)
If index >= 0 Then
Return Me(index)
End If
Return Nothing
End Function
It allow the return of Nothing(null) for T.
The C# equivalent does not work:
public T FindItem(string p_propertyName, object p_value)
{
Int32 index = FindIndex(p_propertyName, p_value);
if (index >= 0) {
return this[index];
}
return null;
}
It won't compile with this error:
The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
'System.Nullable<T>'
I need to be able to have the same functionality or it will break a lot of code. What am I missing?
You can used this method
Used like this
Since
T
can be either reference type or value type, so returningnull
will not satisfy if T is value type. You should return:From the link default keyword:
In case of C# you have to use default(T) and it will return 0 not Nothing or Null if you just return T and not T?.
Now In case of VB.net as per your example you say that you return Nothing which is correct but did you try to check return value of that function.
Like
If you check value of C then it is 0 and not nothing.
Now comes to what happen at MSIL level.
When you compile you VB.net code and check its MSIL. you will find initobj !T and this is instruction for default(T). It is doing this automatically. So if you call your VB.net library from C# then also it will work.