Consider:
public static T GetValueOrDefault<T>(this IDataReader reader, string columnName)
T returnValue = default(T);
I want to implement something like this to check DBNull. I can follow the code fine, but I don't quite understand what static T is in VB.NET. Can someone please explain it a bit?
Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor in C#. A private constructor prevents the class from being instantiated. Because it is sealed, it cannot be inherited.
Shared Methods present a mechanism to make a method available whether or not an instance of a class has been created. Unlike other methods, all functionality and data consumed, processed and returned by a shared method is globl among all instances of the class.
A shared variable or event is stored in memory only once, no matter how many or few instances you create of its class or structure. Similarly, a shared procedure or property holds only one set of local variables. Accessing through an Instance Variable.
Shared procedures are class methods that are not associated with a specific instance of a class. For example, the Cos method defined within the Math class is a shared method. You can call a shared procedure by calling it either as a method of an object, or directly from the class.
The equivalent of static
in VB in Shared
. Shared methods are usually put in Helper classes, because they do not require an instance of the class to run.
The type T indicates that this is a generic method (this is a new feature in VB 9 and C# 3). A generic method effectively takes a type as an argument or returns a generic type.
Extension methods are also new in VB 9/C# 3. These allow you to extend an existing type by adding methods. All you need is a Shared method which is available in the same namespace as your code, and in VB the code has to be in a module, not a normal class.
A module is a class that can't be instantiated and (therefore) only has shared methods. It is declared with the Module keyword in place of the class keyword. Here is your code in VB.
(Also for those that know what's going on "under the covers" strangely setting a value type to Nothing
does compile in VB and is the supported way to get the default value of a value type).
Imports System.Runtime.CompilerServices
<Extension()> _
Public Shared Function GetValueOrDefault(Of T)(ByVal reader As IDataReader, ByVal columnName As String) As T
Dim returnValue As T = Nothing
End Function
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