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.
Related
This is a pretty basic question,
But how does, for example
Console.Write("test");
work?
Console is a class, not an object.
I'm using console as an example because it is commonly used, but I've seen many examples of using Class.method() instead of object.method().
That method is called static method: Static Classes and Static Class Members (C# Programming Guide).
You don't need an instance to call static class member:
A non-static class can contain static methods, fields, properties, or
events. The static member is callable on a class even when no instance
of the class has been created. The static member is always accessed by
the class name, not the instance name. Only one copy of a static
member exists, regardless of how many instances of the class are
created. Static methods and properties cannot access non-static fields
and events in their containing type, and they cannot access an
instance variable of any object unless it is explicitly passed in a
method parameter.
Write is a static method, so you invoke it on the type instead of on an instance. See documentation.
Write is a static method in the Console class, not an instance method.
Console.Write is a static method which writes to the console without adding a new line.
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.
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);
Can you have static and instance methods in the same c# or c++ class ?
If yes, what would be the use of having both, if no why not ?
Yes, of course you can!
Static methods do not pass an implicit this pointer and are used whenever you do not need to operate on a specific instance of that class/type (such as modifying its members).
If you do need to modify a specific instance, you should use an instance method.
There's no reason that these two types of methods cannot be declared together in the same class. If you're using C#, check out some of the classes defined by the .NET Framework. Lots of them have both static and instance methods. That will give you some idea as to how these might be used effectively.
In C++, there's no reason to even create a "static" class (one with all static methods) as you might find in C#. The better approach would be to put the functions into a namespace as free functions. Not everything has to be an "object".
Yes you can.
And lots of uses. Static methods are usually library tools, which can be applied on instances of the class.
Instance methods are methods that you invoke by each specific instance.
Yes, here's a practicle example from the framework itself:
namespace System
{
public struct Int32 //...
{
public const int MaxValue = 2147483647;
//...
public TypeCode GetTypeCode();
public static int Parse(string s);
//...
}
}
Only those members are kept Static that are needed to be shared though each and every object of the same origin class equally, for instance if you have a static method (static method also requires to return a static value of the class), static members are initiated before even you make an object of that class.
now you also asked why and why not, remember there are thousand ways of doing so and thousand reasons if you start thinking in Object-Oriented manner.
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.