VS 2008 Extension methods

  • Thread starter Thread starter Lloyd Sheen
  • Start date Start date
L

Lloyd Sheen

Is it possible to create extension methods based on the generic. Not the
best description so I will expand.

If I have several lists e.g.

dim list1 as list(of object1)
dim list2 as list(of object2) etc.

Can I define an extension method such that it can be used for all List(of
T)?

LS
 
Is it possible to create extension methods based on the generic. Not the
best description so I will expand.

If I have several lists e.g.

dim list1 as list(of object1)
dim list2 as list(of object2) etc.

Can I define an extension method such that it can be used for all List(of
T)?

LS

Sure, make it generic:

Option Strict On
Option Explicit On

Imports System.Runtime.CompilerServices

Module Module1

Sub Main()
Dim l1 As New List(Of Integer)
Dim l2 As New List(Of String)

For i As Integer = 1 To 10
l1.Add(i)
Next

l2.Add("this is a test")
l2.Add("another entry")

Console.WriteLine(l1.MyCount())
Console.WriteLine(l2.MyCount())
End Sub

<Extension()> _
Public Function MyCount(Of T)(ByVal l As List(Of T)) As Integer
Return l.Count
End Function

End Module

HTH
 
Tom Shelton said:
Sure, make it generic:

Option Strict On
Option Explicit On

Imports System.Runtime.CompilerServices

Module Module1

Sub Main()
Dim l1 As New List(Of Integer)
Dim l2 As New List(Of String)

For i As Integer = 1 To 10
l1.Add(i)
Next

l2.Add("this is a test")
l2.Add("another entry")

Console.WriteLine(l1.MyCount())
Console.WriteLine(l2.MyCount())
End Sub

<Extension()> _
Public Function MyCount(Of T)(ByVal l As List(Of T)) As Integer
Return l.Count
End Function

End Module

HTH

Thanks Tom, works great. Will have to get my head around the syntax.

LS
 
Back
Top