This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 8 years ago.
I am wondering if I can use extension method or other techniques to extend static class like
System.Net.Mime.MediaTypeNames.Image, it has fewer type than I need.
No, extension methods can only be used to add instance methods, not static methods (or even properties). Extension methods are really just syntactic sugar around static methods. For instance, when you use an extension method such as Count():
var list = GetList();
var size = list.Count();
This is actually compiled to:
var list = GetList();
var size = Enumerable.Count(list);
You can't add additional static methods to an existing class using extension methods.
No, this is not yet possible in C#, though hopefully it will become so at some point. And you can't subclass a static class and add new methods that way, since static classes must derive from object. One thing you can do though, which produces a pretty similar effect in your code, is simply declare another static class that you will use instead when you want your extension methods. For example:
public static class MessageBox2
{
public static DialogResult ShowError(string Caption, string Message, params object[] OptionalFormatArgs)
{
return MessageBox.Show(string.Format(Message, OptionalFormatArgs), Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Since the original class is static, by definition the "extension" method doesn't need to receive an instance as a this parameter, and can simply use static methods of the original class.
Related
This question already has answers here:
Easiest way to re-use a function without instantiation a new class
(4 answers)
Closed 5 years ago.
I've created a dll, lets call it ExampleHelper.dll.
The structure of the Visual Studio Class Library which I've compiled to dll is the following:
namespace ExampleHelper
{
public class Example
{
public string GetExamples(string input)
{
// stuff
}
}
}
So, I reference it in my other project in which I want to use these ExampleHelper classes, by adding a using line at the top of the file in question:
using ExampleHelper;
Now, I can see that I can access the class from ExampleHelper, which is called Example. But, I can't access the methods in that class, which means I can't write Example.GetExamples("hello"), as it says GetExamples doesn't exist.
I noticed that I can do this:
Example e = new Example();
e.GetExamples("hello");
which I of course can use, but it doesn't feel quite right to instantiate a new object each time I want to use a helper method.
Have I done something completely wrong? My guess is yes, but I can't find where I'm going wrong. Any help appreciated!
Make GetExamples(string input) a static method
public static string GetExamples(string input)
Static methods do not require an instance of the class.
You need to have an instance of Example object to call this method.
To call a method without an instace of a object, method must be static.
public static string GetExamples(string input)
should be the method's declaration.
Please put your class and methods as STATIC, you'll be able to use it everywhere.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
What is the difference between an extension method and a static method ?
I have two classes like this :
public static class AClass {
public static int AMethod(string ....)
{
}
}
and
public static class BClass {
public static int BMethod(this string ....)
{
}
}
I can use these like
AClass.AMethod('...');
or
'...'.BMethod();
Which is proposed ?
An extension method is still a static method. You can use it exactly as you'd use a normal static method.
The only difference is that an extension method allows you to use the method in a way that looks like it's part of the type, so you can write:
int result = stringValue.BMethod();
Instead of:
int result = BClass.BMethod(stringValue);
This works purely as a compile "trick" - the compiler sees the first form, and if the BClass is usable (it has a proper using and is in a referenced assembly), then it will turn it into the second method's IL for you. It's purely a convenience.
Which is proposed ?
This really depends. If you control the type, I'd recommend putting the methods on the type itself. This is typically more maintainable.
If you don't control the type, or you're trying to "extend" a common type (such as IEnumerable<T>), then extension methods may be a reasonable approach.
However, if the type is a very common type, I'd typically avoid extension methods, as they become "noise" in intellisense, which in turn can cause extra confusion. For example, I would personally not recommend adding extension methods on System.Object or System.String, etc.
You cannot override an extension method.
Only if the method has a different signature, then it can be overloaded.
Off course there are some limitations:
Extension Methods have to be implemented as static methods and in static classes (inside a non-nested, non-generic static class to be more precise).
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.
Extension methods cannot access private variables in the type they are extending.
You can consider Extension Methods as a 'legal' way to add more static methods to existing classes without actually inheriting them.
But the funny thing is that unlike regular static methods of the class, you cannot call Extension Methods on a class level (you will get an compile time error if you try this), but instead you must invoke them on a instance of the class (as if they were some regular methods of the instance of that class, which they are not!!!).
Also, inside the Extension Method you can freely use public properties of the passed object instance on which the method is being invoked, you are by no means limited only to static object data. Only the Extension Method is static method, but the object on which is called is full, regular object instance.
This question already has answers here:
What are Extension Methods?
(13 answers)
Closed 10 years ago.
namespace System.Web.Mvc.Html
{
// Summary:
// Represents support for HTML in an application.
public static class FormExtensions
{
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName);
...
}
}
I have noticed that 'this' object in front of the first parameter in BeginForm method doesn't seem to be accepted as a parameter. Looks like in real BeginForm methods functions as:
BeginForm(string actionName, string controllerName);
omitting the first parameter. But it actually receives that first parameter somehow in a hidden way.
Can you please explain me how this structure works. I actually exploring MVC 4 internet Sample.
Thank you.
This is how extension methods works in C#. The Extension Methods feature allowing you to extend existing types with custom methods.
The this [TypeName] keyword in the context of method's parameters is the type that you want to extend with your custom methods, the this is used as a prefix, in your case, HtmlHelper is the type to extend and BeginForm is the method which should extend it.
Take a look at this simple extention method for the string type:
public static bool BiggerThan(this string theString, int minChars)
{
return (theString.Length > minChars);
}
You can easily use it on string object:
var isBigger = "my string is bigger than 20 chars?".BiggerThan(20);
References:
Well-documented reference would be: How to: Implement and Call a
Custom Extension Method (C# Programming Guide)
More particular reference about Extention Methods in ASP.NET MVC would be:
How To Create Custom MVC Extension Methods
Extension Methods:
A "bolt on" way to extend an existing type. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. For instance, you might like to know whether a certain string was a number or not. Or you might want to have the Show() Hide() functionality in ASP.net WebForms for controls.
For Example:
public static class MyExtensionMethods
{
public static void Show(this Control subject)
{
subject.Visible = true;
}
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
Edit:
For futher information you can see the MSDN documentation at: http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx which was kindly linked by #aush.
I enjoyed reading "C# In Depth" regarding Extension Methods. There is an excerpt available here:
http://my.safaribooksonline.com/book/programming/csharp/9781935182474/extension-methods/ch10lev1sec3
You can of course buy the book online or you can just do some research into how it all works under the hood using Google.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are Extension Methods?
I know this questions has been asked previously, but could some provide a non-techy explanation, as simple as possible in laymens terms.
All of documentation on other answers seems to be a little far out for me
Extension methods are a way of simulating new methods on a type without actually changing the type definition itself.
I guess a layman way of explaining it is that it gives every type it's own personal entourage. They person itself is not modified they just gain a host of new abilities simply by virtue of the people who are paid to hang out with them.
I don't think it gets much simpler than the one sentence from the Wikipedia article:
"Extension methods enable you to 'add' methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type."
Well, programming is inherently "techy", so I would try to learn as much as you can in order to understand the documentation. However, extension methods simply allow you to add methods that act like instance methods to an existing class that would otherwise be closed for modification.
For example, if I wrote a library that included a type Foo and did not distribute the source code you would be stuck subclassing it to add any functionality, and that would only be possible if I left the type "unsealed". With the advent of extension methods you are able to add methods to the class that you can call as you would any other method (in reality they are implemented as static methods that take a hidden first parameter to an instance of Foo, so you still don't have access to private members of the class).
Extension methods allow you to add functionality (methods) to classes you have no access to their source.
You can define a simple class:
public class A
{
public void B()
{
Console.WriteLine("B called");
this.C();
}
public void C()
{
Console.WriteLine("C called");
}
}
But what if you get A defined as:
public class A
{
public void C()
{
Console.WriteLine("C called");
}
}
And you want to add function B to it? You use extension methods to do it:
public class A
{
public void C()
{
Console.WriteLine("C called");
}
}
// the extensions class, can be any name, must be public
public class Extensions
{
public static void B( this A me)
// ^ must be public static ^ indicates extension ^ type to extend ^ name of variable instead of this
{
Console.WriteLine("B called");
// instead of this, you use the name of variable you used in the parameters
me.C();
}
}
Now you can call A.B() as it was in the first example.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does “this” mean in a static method declaration?
i go through a code snippet and found this keyword is used as function argument.
the code snippet is like
public static void AddCell(this Table table, object cell)
why AddCell has this keyword they can write likeAddCell(Table table, object cell)
please explain the situation when to use this keyword as function argument with small code sample as a result i can better understand. thanks.
Basically what is being defined in your example is an extension method. In a static method, if you define the first argument using the this keyword you are allowing the method to be called on instance objects of the type defined on the first argument.
In the example you stated you would be able to do something like this:
Table someTableInstance; /// must be instanciated somehow;
someTableInstance.AddCell(cell); // Call the AddCell method as if it was an instance method.
Hope it helps,
Regards,
Bruno
This syntax is used for extension methods.
These look a bit odd when you first see them written, but they are fabulous things - most of Linq is written as extension methods.
Here's a good intro tutorial - http://csharp.net-tutorials.com/csharp-3.0/extension-methods/ - which includes the example:
public static class MyExtensionMethods
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
which enables you to call:
"fred".IsNumeric()
this is the keyword for creating extension methods.
This way, while I have not changed the implementation of Table, I can call method AddCell on a member of Table.
MSDN:
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.
For client code written in C# and
Visual Basic, there is no apparent
difference between calling an
extension method and the methods that
are actually defined in a type.
It's a declaring an extension method. The point is that as well as
MyStaticClass.AddCell(table, cell);
you can now just call
table.AddCell(cell);
assuming MyStaticClass is in the current namespace or namespaces you've usinged.
The 'this' keyword is used to create an extension method. For instance, if you are using a library class that you want to add a method to without inheriting a new derived type, you can create a static extension method. It is syntactical-sugar that places a regular static method onto an already known type.
For example:
public static int ToNumber( this string numberString )
{
int convertedInt = 0;
// logic goes here to convert to an int
return convertedInt;
}
Can be called like this:
string myNumberString = "5";
int num = myNumberString.ToNumber();
You didn't have to create an inherited class to do this but it reads cleanly.