I’ve been watching the ASP.NET MVC Storefront video series again and saw something that I’ve never noticed or payed any attention to before. I noticed there were a lot of references to this in the signature lists of various methods. Here is an example of one:
public static Category WithCategoryName(this IList<Category> list, string categoryName)
{
return
(
from s in list
where s.Name.Equals(categoryName, StringComparison.InvariantCultureIgnoreCase)
select s
)
.SingleOrDefault();
}
I immediately understand the IList<Category> list and the string categoryName in the signature, but was confused about what this does.
So, being a 95% VB guy, I popped the code into my favorite converter and got:
<System.Runtime.CompilerServices.Extension>
Public Shared Function WithCategoryName(list As IList(Of Category), categoryName As String) As Category
Return
(
From s In list
Where s.Name.Equals(categoryName, StringComparison.InvariantCultureIgnoreCase)
Select s
)
.SingleOrDefault()
End Function
First of all, I’m not totally sure why <System.Runtime.CompilerServices.Extension> was included, maybe it’s just the converter, nevertheless, as you can see, this wasn’t converted into anything that I can tell unless it has to do with the aforementioned <System.Runtime.CompilerServices.Extension>.
So the questions are:
- What does
thisactually refer to and/or do in the C# method signature? - Is there a VB.NET equivalent?
Response to Question 1:
So we’ve definitely clarified that this does in fact denote an extension method and that from the answers given, it seems there’s no inline VB equivalent.
I would like to add that since I mentioned the ASP.NET MVC Storefront video, the C# example above was pulled from his CategoryFilters class. I assume this is how you implement what was referenced as a pipes and filters or pipeline methodology.
Response to Question 2:
I assume VB.NET’s way of handling extension methods is something like this for example:
Imports System.Runtime.CompilerServices
Public Module StringExtensions
<Extension()> _
Public Function IsNullOrBlank(ByVal s As String) As Boolean
Return s Is Nothing OrElse s.Trim.Length.Equals(0)
End Function
End Module
That is an extension method. The
thisspecifies that it is an extension method ofthis <parameter>type, in your case,IList<Category>.There is a VB.NET equivalent here, though it is an attribute, not a keyword.
Extension methods need to know the type to apply to, note that this is apparent with generics. An extension method:
Will not be available on anything other than
List<Category>.