Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic function question

How to understand the following code? What does "this" mean in the generic function prototype? Thanks!

public static class MyExtensions
{
    public static MyStream<T> MySingle<T>(this T source)
    {
        return new MyStream<T>(source);
    }
}
like image 225
david Avatar asked Aug 25 '10 20:08

david


3 Answers

this in this context means it is an extension method so you can either use it the "normal" way:

MyExtensions.MySingle(someSource)

or this (sometimes nicer) way:

someSource.MySingle()

This is only possible when the method is static and is in a static class. Also, it have nothing to do with the generic aspect of the method - you can make extension methods without generics aspects and you still have the this in front of the parameter.

Extension methods, as the name suggest, is used for extending already existing classes with methods if you don't have access to the source or if you want it to be used over a broad set of classes. It is important to note, that you don't get access to private and protected methods etc., like when you derive from the class, when you make a extension method on a type.

Also, for a in-depth explanation:

Extension Methods (C# Programming Guide)

like image 63
Lasse Espeholt Avatar answered Sep 24 '22 21:09

Lasse Espeholt


That it is an extension method, that becomes a valid method of all objects of type T.

It has nothing to do with generics.

like image 20
Albin Sunnanbo Avatar answered Sep 21 '22 21:09

Albin Sunnanbo


MySingle<T> is defined as an extension method (MSDN).

This means that in usage you can call it like this:

MyStream<string> stringStream = "a string".MySingle();

This is identical to calling it in the "standard" way:

MyExtensions.MySingle("a string");

When you call it the first way (as an extension method), the item on which it is called is passed as the first parameter. The type of the first parameter therefore defines the type on which the extension method can be called, but since you have an open generic type, it can be called on any object.

To define an extension method, the containing class and the method itself must be declared static.

Extension methods were added in C# 3.0 and VB 9.0.

like image 24
Jay Avatar answered Sep 23 '22 21:09

Jay