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.
Related
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);
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.
I know (or so I hear) that writing extension methods for a single stand alone .net class (not an implementation of IEnumerable) is potential code smell. However, for the sake of making the life easier I need to attach a method to the ConfigurationManager class in asp.net. It's a static object so this won't work:
public static List<string> GetSupportedDomains(this ConfigurationManager manager)
{
//the manager needs to be static.
}
So the question is - is it possible to write an extension method for a static class in .net?
No, it isn't possible.
They are defined as static objects that appear to be instance methods.
From MSDN:
Extension methods are defined as static methods but are called by using instance method syntax.
No you can not. Extension methods require an instance of a given type, which you cannot get from a static class.
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 .
In C#, what is the purpose of marking a class static?
If I have a class that has only static methods, I can mark the class static or not. Why would I want to mark the class static? Would I ever NOT want to mark a class static, if all the methods are static, and if I plan to never add a non-static method?
I looked around and saw some similar questions, but none that were just like this.
Marking a class as static is a declarative statement that you only intend for this type to have static and const members. This is enforced by the compiler and prevents you from accidentally adding an instance method to the type.
Other advantages
Extension methods can only be defined in static classes
Prevents users from creating an instance of the class
Prevents use of the type as a generic argument (thanks Eric!)
Marking a class as static gets you two important things.
Compiler verification that you only put static members in a class.
An obvious statement to readers of your code that this class is only a container for static members.
The feature was invented in response to a bug in NDP v1.0, where a un-callable non-static member was included in the System.Environment class.
If you would like to write extension methods, you have to use a static class. Otherwise it is to show the class will never have any instance data.
It is a convention specific to the C# language, the CLR has no notion of static classes. It ensures that you cannot accidentally add an instance member in the class, cannot inherit the class and client code cannot accidentally create an instance of the class. The underlying TypeAttributes for the class are Abstract and Sealed. Abstract ensures that the new operator can't work, Sealed ensures that you can't inherit from the class.
Also by convention, extension methods must be static members of a static class. VB.NET does it differently, it requires the [Extension] attribute.
Using static classes in your code is not necessary, but it is useful. Their contract is very descriptive, it makes your code easier to understand. But be careful not to use them as a vehicle to write procedural code instead of OOP code.
You mark a class static if you want to force it to contain only static methods, a typical helper class. If you put an instance method the compiler will complain - this is good. In version 1 of the .NET framework there was a class, don't remember which one, that was meant to ship with only static methods. Accidentally one of those methods did not get the static modifier. Because this feature did not exist at the time the bug was spotted very late, after shipping. They did make the constructor private and as such the method could not be used.