Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
VB.NET: Type extensions
From Wiki
One of the best features after LINQ in Visual Studio 2008 is type extensions. Extensions permit developers to take function based code to method base code.
Function base example
- Dim ExampleNumber As String = "100"
- Console.WriteLine(Convert.ToInt32(ExampleNumber))
Method base example (uses extensions)
- Dim ExampleNumber As String = "100"
- Console.WriteLine(ExampleNumber.ToInteger)
Let's look at the underlying source code which will assist in understanding extensions. An extension begins with the attribute tag of <Extension> from the System.Runtime.CompilerServices namespace. The parameter value is the variable using the extension i.e. ExampleNumber, the variable in the example is value.
- <Extension()> _
- Public Function ToInteger(ByVal value As String) As Integer
- Return Convert.ToInt32(value)
- End Function
- <Extension()> _
- Public Function ToInteger(ByVal value As Boolean) As Integer
- Return Convert.ToInt32(value)
- End Function
To pass a value to the extension a second parameter is required. The first example simple increments a string by one while the second example allows the amount to increment by.
- <Extension()> _
- Public Function Increment(ByRef value As Int32) As Int32
- Return value + 1
- End Function
- <Extension()> _
- Public Function Increment(ByRef value As Int32, ByVal Amount As Int32) As Int32
- Return value + Amount
- End Function
A word of advice, all the examples shown have no exception handling or type checking, this is a decision you need to make up front. If you decide to there are various avenues such as using another extension as shown below.
- <Extension()> _
- Public Function IsInteger(ByVal value As String) As Boolean
- Return System.Text.RegularExpressions.Regex.IsMatch(value, "^[-+]?\d+$")
- End Function
When writing extensions it is best to take time to consider what should be an extension along with taking time to write them properly rather than simply using them because they are a new edition to the language.
Below are some suggestions for everyday use. Some are my creations while others were found on the web copied as found or modified slightly.
- <Extension()> _
- Public Function Format(ByVal value As Double) As String
- Return value.ToString("F2")
- End Function
- <Extension()> _
- Public Function Format(ByVal value As Double, ByVal Places As Integer) As String
- Return value.ToString(String.Format("F{0}", Places))
- End Function
- <Extension()> _
- Public Function ToDouble(ByVal value As String) As Double
- Return Convert.ToDouble(value)
- End Function
- <Extension()> _
- Public Function Increment(ByRef value As String) As Int32
- Return value.ToInteger + 1
- End Function
- <Extension()> _
- Public Function Decrement(ByRef value As String) As String
- Return CStr(value.ToInteger - 1)
- End Function
- <Extension()> _
- Public Function Decrement(ByRef value As Int32) As Integer
- Return value - 1
- End Function
- <Extension()> _
- Public Function Increment(ByRef value As Int32) As Int32
- Return value + 1
- End Function
- <Extension()> _
- Public Function RightAlign(ByVal value As String, ByVal Spaces As Int32) As String
- Return String.Format("{0," & Spaces & "}", value)
- End Function
- <Extension()> _
- Public Function LeftAlign(ByVal value As String, ByVal Spaces As Int32) As String
- Return String.Format("{0,-" & Spaces & "}", value)
- End Function
- <Extension()> _
- Function TabStop(ByVal value As String) As String
- Return value & System.Text.RegularExpressions.Regex.Unescape("\t")
- End Function
- <Extension()> _
- Public Function ProperCase(ByVal value As String) As String
- Dim TI As System.Globalization.TextInfo = New System.Globalization.CultureInfo("en-US", False).TextInfo
- Return TI.ToTitleCase(value.ToLower)
- End Function
- <Extension()> _
- Public Function ToDate(ByVal value As String) As Date
- Dim Parts As String() = value.Split(",".ToCharArray)
- Dim Year As Integer = Parts(0).ToInteger
- Return New DateTime(Parts(0).ToInteger, Parts(1).ToInteger, Parts(2).ToInteger)
- End Function
- <Extension()> _
- Public Sub PrintToConsole(ByVal dv As DataView, ByVal ColumnName As String)
- For i As Integer = 0 To dv.Count - 1
- Console.WriteLine("".TabStop & dv(i)(ColumnName).ToString())
- Next
- End Sub
I do not use CheckBox columns in DataGridViews very much and when wanting to know if a column is checked or not say in the CellContentClick event I need only point to a simple extension.
- <Extension()> _
- Function CurrentRowCheckBoxValue( _
- ByVal GridView As DataGridView, _
- ByVal ColumnName As String) As Boolean
- GridView.EndEdit() ' Must be here else you will not get the proper value
- Return Convert.ToBoolean( _
- GridView.Rows(GridView.CurrentRow.Index).Cells(ColumnName).Value)
- End Function
Example, we have a CheckBox column in a DataGridView named CheckList.
- Private Sub DataGridDemo_CellContentClick( _
- ByVal sender As Object, _
- ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
- Handles DataGridView1.CellContentClick
- Dim GridView As DataGridView = DirectCast(sender, DataGridView)
- If GridView.CurrentRowCheckBoxValue("CheckList") Then
- ' Do something
- End If
Here is an extension which used LINQ to search for text in a specific column in a DataGridView by ColumnName. I have overloaded this to also search by Column Index and close matches but showing one version to keep things in target and simple to understand.
- <Runtime.CompilerServices.Extension()> _
- Public Function Seek(ByVal GridView As DataGridView, _
- ByVal ColumnName As String, ByVal Value As String, _
- ByVal f As Form) As Boolean
- Dim Located As Boolean = False
- If GridView.Columns.Contains(ColumnName) Then
- Dim SingleRow As DataGridViewRow = _
- (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() _
- Where Rows.Cells(ColumnName).Value.ToString() = Value).FirstOrDefault
- If Not IsNothing(SingleRow) Then
- If GridView.CurrentCell.RowIndex <> SingleRow.Index Then
- GridView.CurrentCell = GridView(0, SingleRow.Index)
- End If
- Located = True
- f.ActiveControl = GridView
- End If
- Return Located
- Else
- Throw New Exception("Column '" & ColumnName & _
- "' not contained in this DataGridView")
- End If
- End Function
Example usage. The DataGridView has a ID Column where the text is upper cased. If a match to the text in Textbox1 is found we activate the grid and position to the row we found the match on. Note the column is hard coded but with minor changes we could always set the column to match the column name we are searching on. If no match we make the textbox the active control.
- Private Sub cmdFind_Click() Handles cmdFind.Click
- If Not DataGridView1.Seek("ID", TextBox1.Text.ToUpper, Me) Then
- ActiveControl = TextBox1
- End If
- End Sub
Consider the following extension, the intent here is to make the code using this code easier to read as we could have created a function or done the code inplace I favored implementing as an extension.
- <Runtime.CompilerServices.Extension()> _
- Function RemoveDoubleQuotes(ByVal value As String) As String
- If String.IsNullOrEmpty(value) Then
- Return String.Empty
- End If
- Return System.Text.RegularExpressions.Regex.Replace(value, "[""]", String.Empty)
- End Function
- <Runtime.CompilerServices.Extension()> _
- Function RemoveDoubleQuotes(ByVal value As String, ByVal Replacement As String) As String
- If String.IsNullOrEmpty(value) Then
- Return String.Empty
- End If
- Return System.Text.RegularExpressions.Regex.Replace(value, "[""]", Replacement)
- End Function
- <Runtime.CompilerServices.Extension()> _
- Function RemoveSingleQuotes(ByVal value As String) As String
- If String.IsNullOrEmpty(value) Then
- Return String.Empty
- End If
- Return System.Text.RegularExpressions.Regex.Replace(value, "[']", String.Empty)
- End Function
- <Runtime.CompilerServices.Extension()> _
- Function RemoveSingleQuotes(ByVal value As String, ByVal Replacement As String) As String
- If String.IsNullOrEmpty(value) Then
- Return String.Empty
- End If
- Return System.Text.RegularExpressions.Regex.Replace(value, "[']", Replacement)
- End Function
See Reading SQL from embedded resources using VS2008 extensions here [1]



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.