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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

ArrayList memory problem 3
ArrayList 1
Extension Methods in VB 2008 Express? 4
Funny Error 2
Generic method & constraint 10
Where is Web Method 3
Generic Constraints Question 10
(New Object).Method 4

Back
Top