C# generic function question - c#

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);
}
}

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)

That it is an extension method, that becomes a valid method of all objects of type T.
It has nothing to do with generics.

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.

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

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.

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

Related

Extension method is not working,If method in nonstatic class? [duplicate]

This question already has answers here:
Why are extension methods only allowed in non-nested, non-generic static class?
(3 answers)
Closed 9 years ago.
Just now i read about Extension methods.I created static method inside static class its working fine.
static class ExtensionMethods
{
public static string splitFirstName(this string strName)
{
return strName.Split(" ".ToCharArray())[0];
}
}
But If i create static method inside Nonstatic class its not working.
class NonStaticCls
{
public static string splitFirstName(this string strName)
{
return strName.Split(" ".ToCharArray())[0];
}
}
Please tell why its not working in nonstatic class.
Please tell why its not working in nonstatic class.
Because that's just how extension methods are specified. They must be declared in a non-nested, non-generic class.
From section 10.6.9 of the C# 5 specification:
When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes. The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.
Why do you want to declare it in a non-static class? What are you trying to achieve which can't be achieved equally well using a static class? (I can just about imagine some possibilities, but they're not things I've ever wanted to do in extension methods myself...)
It's a requirement that the class be static. This is reasonable. If it wasn't a static class, you'd be able (potentially) to create instances of that class. But then it has extension methods in it, possibly for other, completely unrelated classes. That could be very confusing.
That's by design behavior. Extension method can only be declared in static class.
How to: Implement and Call a Custom Extension Method (C# Programming Guide)
To define and call the extension method
Define a static class to contain the extension method.
Looks like it's by design.
From MSDN;
The following list provides the main features of a static class:
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
Check out this answer from Eric Lippert
Why are extension methods only allowed in non-nested, non-generic static class?
Also from AskJonSkeet
It's dictated in the language specification, section 10.6.9 of the C#
4 spec:
When the first parameter of a method includes the this modifier, that
method is said to be an extension method. Extension methods can only
be declared in non-generic, non-nested static classes. The first
parameter of an extension method can have no modifiers other than
this, and the parameter type cannot be a pointer type.
According to C# spec. you can read more here Extension Methods
Extension methods can only be declared in non-generic, non-nested
static classes.
AS other pointed you, you need to include the static.
basically you will create a bunch of extension method as Utility Project or Helper Class
Creating static class you need not to instantiated, and invoke the method directly. for Eg. Math.Pow()
as per your question, Extension method work only when it's in Static class. and use of proper namespace.

C# static function with this as parameter to Java function

I got a C# project which needs to be rewritten to java. Unfortunately the original programmer cannot be reached and I have some troubles with some of the C# specific things in the project.
Lets say we have a class in C# like:
public static class MySampleClass : Object
{
...
public static IEnumerable<MyObject> MyFunc(this MyObject t) {
//a lot of code
}
...
}
I dont understand the this before the parameter in this function. What does it reference to? I mean we're in a static class and a static function, so whats "this"? Is it just a reference to t then?
And of course my question would be that this function header is substitute for this in Java:
public static Iterable<MyObject> MyFunc(MyObject t)
Or do I need to do anything else?
Thank you for your help
In this case this refers to any instance of MyObject. It's called extension method:
Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type. Extension methods are a special kind of
static method, but they are called as if they were instance methods on
the extended type.
It defines a method which can be used on instances of MyObject class. There is no such thing in Java, so you have to add this method to MyObject class.
Extension methods, like walkhard pointed out in his answer, can be declared anywhere and can simply be called like if they had been declared within the class.
This does not exist in Java. You will have to add MyFunc to the declaration of that Java class.
Using this in that way makes the method an extension method. Java does not have an equivalent. In C#, it is syntactic sugar that lets you do the same thing as this:
MySampleClass.MyFunc(myObject);
With this code:
myObject.MyFunc();
(These compile to the same thing, as long as MySampleClass's namespace is imported and MyObject doesn't declare its own MyFunc() method.)
Since this doesn't exist in Java, you should simply replace myObject.MyFunc() with MySampleClass.MyFunc(myObject).
It's an extension method it permit to any object of type MyObject to expose the method MyFunc and use it as a normal instance method (but in reality it's not) it's a normal class method
MyObject o=new MyObject();
//whitout extension method
MyObject.MyFunc(o);
//with extension
o.MyFunc();
It's a syntactic sugar that doesn't exist in java so you have to modify class MyObject and adding instance method MyFunc if you don't want to change all the calls to MyFunc or write a static function and modify every call to MyObject.MyFunc(o);

what does "this" reserved word do in C# in parameters field?

I saw things like this:
public static void FunctionSample(**this** Class1 x, int r, double f){
what does "this" do?
Ths means an extension method to Class1, although in current form its incorrect since the method needs to be static as well and inside a static class.
Extension Methods (C# Programming Guide)
Extension methods are defined as static methods but are called by
using instance method syntax. Their first parameter specifies which
type the method operates on, and the parameter is preceded by the
this modifier.
It means that the method you're creating is an extension method. This means (in your case) that the method will act as if it were a member method of Class1. So you could just use this:
Class1 exmpl = new Class1();
exmpl.FunctionSample(0, 0.0);
However, it won't work in your case, since extension methods need to be static, and exist in a static class.
If you want the extension methods to work like the example given above, you will need a using directive to the namespace the static class containing the extension methods is in.
In fact, this is how linq works as well. If you add using System.Linq to your code file, the only thing you're doing is importing a load of extension methods.

Do I have to create extension methods if I want to add type constrained (T=int) method onto a generic (T) class?

for example, I have a (non-static) class Foo<T>
I would like to add a method bar() for Foo, however this method should only work for Foo<int>.
Because we cannot overload type constraints,
Do I have to create an extension method in a separate static class bar(this Foo<int> myFoo)?
Basically, yes. C# (and the CLR in general) does not support template specialization known from C++.
Type parameters are meant to be used when your class'es implementation doesn't care about the actual type at all.
As an alternative, add a runtime check to make sure the method is only being called on typeof(T) == typeof(int).

Extension method - having to use this keyword?

I have added an extension method to the ASP.NET System.Web.UI.Page.
Every page in my application inherits from this class.
I cannot just access the extension method, however. I must type this.MyMethod(); instead of just being able to use MyMethod(). I thought that methods/attributes of this were inherently in the default scope. What am I not understanding? Or is this a nuance of extension methods?
I thought that methods/attributes of
this were inherently in the default
scope.
They are. But extension methods are not methods of this in the default scope; they are static methods accessible via syntactic sugar provided as a courtesy by the compiler.
I believe you already know this, but just to clarify: if ExtensionMethod is an extension method of the class whose scope you're currently in, typing this:
this.ExtensionMethod();
...is the same as:
SomeStaticClass.ExtensionMethod(this);
this needs to be passed as a parameter to ExtensionMethod. The first way above, the compiler simply does this for you.
Naturally, they could have implemented things differently so that the compiler "brings in" extension methods as well as class members into the default scope; they just simply chose not to. Personally, I like that; but I guess it's a subjective matter. Anyway, if you dislike having to type this, it's only a small annoyance, right?
is this a nuance of extension methods?
Yes, it is. (As others have explained.)
If you want to use the method without any qualification, then you could just make a class that inherits from Page and includes your method (minus the first paramater, of course). Then make each page in your application inherit from your new custom page.
In order to use extension method you should declare:
using Namespace.Where.Extension.Method.Is.Located
And don't forget that class that holds extension method should be static.

Categories