views:

185

answers:

6

Hi,

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);
    }
}
+7  A: 

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

It has nothing to do with generics.

Albin Sunnanbo
Good point about the `this` keyword being unrelated to generics.
Oded
+16  A: 

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)

lasseespeholt
+1  A: 

This is an extension method, this is the instance that the method is applied to.

Christopherous 5000
A: 

This indicates it is an extension method. The type being extended is 'T'. All instances of 'T' will have method MySingle .

Yogendra
+2  A: 

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.

Jay
+1  A: 

Yes it is an extention method but as far as i understand he is also asking what does it mean using a T (generic type definition) with "this" keyword in the method signature.

It means that the extention method will be valid method for all objects of every class and struct types in your project.

orka