This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 2 years ago.
I know i can do the below to extend a class. I have a static class i would like to extend. How might i do it? I would like to write ClassName.MyFunc()
static public class SomeName
{
static public int HelperFunction(this SomeClass v)
You can't have extension methods on static classes because extension methods
are only applicable to instantiable
types and static classes cannot be
instantiated.
Check this code..
public static bool IsEmail(this string email)
{
if (email != null)
{
return Regex.IsMatch(email, "EmailPattern");
}
return false;
}
First parameter to IsEmail() is the extending type instance and not just the type itself. You can never have an instance of a static type.
You can't extend static classes in C#. Extension methods work by defining static methods that appear as instance methods on some type. You can't define an extension method that extends a static class.
You might want to turn your static class into a singleton. Then there will only be one instance of the class. And you can use extension methods on it because it's an instance.
This is provided you have access to the source code of the class.
Related
I have been learning C# for two weeks now, though it is not my first either second language. I have been wondering about the static word. I know I should have researched about this word long before...but this is the first time I realized how much confusing this word is for me. For what I have read:
A static class is a class which does not need to be instanciated to be used (
Class with single method -- best approach? ). This may have some advantages and some disadvanatges regarding testing, polymorphism etc.
But the static word can be applied also to classes, fields, methods, properties, operators, events and constructors !!! ( https://msdn.microsoft.com/en-us/library/98f28cdx%28v=vs.80%29.aspx ). Example:
Property:
private static string s = "";
Method:
public static void helperMethod() {
Console.WriteLine("Whatever");
}
Does the word static have a global meaning or employed in differents parts of the code the meaning can change?
class modifier
When static is applied to a class it indicates four attributes.
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
property or function modifier (and events and methods)
When applied to properties and functions, e.g.
public Thing
{
static int SharedCount { get; set; }
static string GenerateName()
{
// ...
}
}
it means that the properties and functions will be accessible via the type name, without instantiating the class. This properties and functions will not be accessible via an instance of the class. So, both
var i = Thing.SharedCount;
var s = Thing.GenerateName();
Are valid and correct statements, Where as
var i = new Thing().SharedCount;
var s = this.GenerateName();
are both incorrect.
Code in functions and properties declared with the static modifier cannot access non-static members of the class.
member variables
Member variables declared with a static modifier, e.g.
class Thing
{
private static int sharedCount = 0;
private static readonly IDictionary<string, int> ThingLookup =
new Dictionary<string, int>
{
{ "a", 1 },
{ "b", 2 }
};
}
are shared by all static functions and properties and by all instances of the class.
static constructors
When applied to constructors, e.g.
class Thing
{
static Thing()
{
\\ Do this once and first.
}
}
static means the constructor will run once per AppDomain, when the type is first accessed. There are special edge cases around this.
operators
When an operator is overloaded for a type, this is always declared as static, e.g.
public static Thing operator +(Thing left, Thing right)
{
// Something special to do with things.
}
It is not logical for this to be declared at an instance level since operators must apply to types.
These distinctions are explained here, here, here and here.
Static members are items that are deemed to be so commonplace that there is no need to create an instance of the type when invoking the member. While any class can define static members, they are most commonly found within utility classes such as System.Console, System.Math, System.Environment, or System.GC, and so on.
Also the static keyword in C# is refering to something in the class, or the class itself, that is shared amongst all instances of the class. For example, a field that is marked as static can be accessed from all instances of that class through the class name.
Quick answer: No static remains the same contextually everywhere :
From dotnetperls:
These are called with the type name. No instance is required—this makes them slightly faster. Static methods can be public or private.
Info:
Static methods use the static keyword, usually as the first keyword or the second keyword after public.
Warning:
A static method cannot access non-static class level members. It has no this pointer.
Instance:
An instance method can access those members, but must be called through an instantiated object. This adds indirection.
C# program that uses instance and static methods
using System;
class Program
{
static void MethodA()
{
Console.WriteLine("Static method");
}
void MethodB()
{
Console.WriteLine("Instance method");
}
static char MethodC()
{
Console.WriteLine("Static method");
return 'C';
}
char MethodD()
{
Console.WriteLine("Instance method");
return 'D';
}
static void Main()
{
//
// Call the two static methods on the Program type.
//
Program.MethodA();
Console.WriteLine(Program.MethodC());
//
// Create a new Program instance and call the two instance methods.
//
Program programInstance = new Program();
programInstance.MethodB();
Console.WriteLine(programInstance.MethodD());
}
}
Output
Static method
Static method
C
Instance method
Instance method
D
In C#, data members, member functions, properties and events can be declared either as static or non-static.
Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.
Static members are often used to represent data or calculations that do not change in response to object state.
Static can be used in following ways:
Static data members
Static constructor
Static Properties
Static methods
More references :
MSDN
Static
Static in c#
What is static ?
The static keyword means generally the same everywhere. When it is a modifier to a class, the class's members must also be marked static. When it is a modifier to a member, (fields, properties, methods, events etc.) the member can be accessed using the following syntax:
ClassName.memberName
Note that operators must be declared static and extension methods must be in a static class which means it also has to be static.
Word static speaks for itself. If you have something that may change for every new object of some type - it's instance member and if it stays the same for all instances - it's static member.
From MSDN :
It is useful to think of static members as belonging to classes and
instance members as belonging to objects (instances of classes).
Source : static and instance members
Static members can be accessed via class object, something like MyClass.MyMember when instance members are only accessible on instance of a class (new MyClass()).MyMember
It's obvious that compiler takes some time to create instance and only then you can access its properties. So instance members works slower than static members.
In simple words , static property is not being changed across the classes , if your static member is affecting multiple classes once you change the value of it, it will be changed in every single class that is being affected by it.
Static method has to be static if you tend to use it in a static context (static class or so..)
Static class is the one which cannot be instantiated, e.g. static class Car{} this car will always have the same properties ( colour, size...)
There are many concepts related to Static keyword.
This answer will resolve your confusion about static.
This question already has answers here:
How to instantiate an object with a private constructor in C#?
(4 answers)
Closed 7 years ago.
I want to access some of the private members of a class which has its constructor defined as private. How do I create the PrivateObject for such class so that I can access its private members ?
I tried something like this but I cannot instantiate the class "MyClass1" so I am not able to instantite the PrivateObject.
MyClass1 myClass = new MyClass1(); //gives compilation error
PrivateObject po = new PrivateObject(myClass); //gives compilation error
Is there any workaround for this ?
Class with private constructor can only create itself from its own static method. For example:
class MyClass1
{
private MyClass1()
{
}
public static MyClass1 CreateInstance()
{
return new MyClass1();
}
}
It's private members like fields or properties are always accessible only from inside of the class (unless you make some tricks with reflection). If the field is protected you can access it by deriving from this class. All other way it's by design created to restrict access to those fields and you should not try accessing them from the outside.
Edited: now I noticed you use PrivateObject class which is created to make reflection trickes mentioned above. So now you only need to create instance. You should check what is the designed way of initializing this object probably by some static method?
Or check this link for more hacks with reflaction and using Activator: http://www.ipreferjim.com/2011/08/c-instantiating-an-object-with-a-private-constructor/
Can we have some relation between extension methods and inheritance?
Or is an extension method similar to using the new-keyword in C#?
No to both questions. An extension method is actually a method that takes the object the extension operates on as first parameter.
The new keyword is used to allocate resources for an instance of a class. An extension method operates on an instance, but cannot act as a new-replacement, simply because it requires an instance (or null of that type) as a first parameter.
Consider:
public static class StringExtensions
{
public static string Reverse(this string _this)
{
// logic to reverse the string
}
}
You can call this static method in two ways:
// as an extension method:
string s = "hello world";
string t = s.Reverse();
// as a static method invocation:
string t = StringExtensions.Reverse(s);
In either case, the compiler changes the call in MSIL to map the second call. After compiling, there's no way you would recognize an extension method from it's static counterpart without the this-keyword.
To summarize
Extensions are not part of the class
Extensions have no relation to inheritance, in fact they are static methods, which are not inherited
Extensions cannot instantiate classes like the new keyword does (but inside the method you can of course instantiate classes).
Extension can operate on null, where otherwise a method of that class would raise a NullReferenceException. This follows from the fact that the instance is simply the first parameter in the static method.
It is possible to extend sealed classes (like string above), which is not possible through inheritance (you cannot derive from sealed classes).
EDIT:
Tigran and Floran hinted that this question is about the new modifier, and I added it might even be about the new generic constraint.
An extension method has no relation with either meaning of the new keyword. Here are, however, some thoughts in relation to each other. I hope it doesn't confuse matters more. If so, stick to the part above "EDIT" ;)
On the new modifier:
the new modifier is used to hide existing methods. An extension method can never hide existing methods, because the declaration is a static method. You will not even get a compile time warning or error when you do.
The new modifier requires that the method (or property) already exists and is accessible. An extension method can only work if the method with the same signature does not already exist.
The new modifier operates on an extension of the class through inheritance, i.e., every method is already inherited. An extension method operates on an instance of the class and has no inheritance relationship with the class.
On the new generic constraint:
the constraint limits the allowed generic types to those with an accessible parameterless constructor. An extension method has nothing to do with generics.
an extension method itself van be generic and the parameters (i.e., the allowed classes it operates on) can be limited by the new generic constraint:
// this ext. method will only operate on classes that inherit
// from ICollectible and have a public parameterless constructor
public static int CalculateTotal<T>(this T _collectible)
where T : ICollectible, new()
{
// calculate total
}
No, extension method simply extends the functionality of already existing class.
Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type.
See MSDN on Extension Methods (C# Programming Guide).
The new keyword is needed to allow you to override non-virtual and static methods from the base class.
public class A
{
public virtual void One();
public void Two();
}
public class B : A
{
public override void One();
public new void Two();
}
B b = new B();
A a = b as A;
a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B
Check out this link on new vs override.
No. An extension method is syntactic sugar for a separate, static class that takes, as its first argument, an object of the type that is being "extended." It isn't related to inheritance at all. The method only has access to the public members of the "extended" class, just like any other class would.
Extension methods are not related to inheritance or new keyword (or constructors). They allow for nicer code if you want to add some functionality to a class you do not have source code for. It also works if you do have the source code but then it is usually better to just change the source code.
For example you might like to be able to do this:
string text = "this is my string";
int count = text.WordCount();
This method does not exist in the String class and you need to do it like that:
string text = "this is my string";
int count = MyCommon.WordCount(text);
where WordCount() is a static method in some sort of common library of yours.
But with the extension methods you can also do this:
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
and then text.WordCount() will work just as if it was normal method defined in the String class. It just makes things a bit nicer to use.
Code taken from here which I suggest to read as well.
I get the following compilation error at the class name.
Extension method must be defined in a non-generic static class
I am not using normal class. What could be the reason for this. I don't know and don't want to use extension methods.
As requested, here is my comment as an answer:
Without your code there isn't much we can do. My best guess is that you accidentally typed "this" somewhere in a parameter list.
Sample for extension method
public static class ExtensionMethods {
public static object ToAnOtherObject(this object obj) {
// Your operation here
}
}
I had the same problem, and solved it as follows. My code was something like this:
public static class ExtensionMethods
{
public static object ToAnOtherObject(this object obj)
{
// Your operation here
}
}
and I changed it to
public static class ExtensionMethods
{
public static object ToAnOtherObject(object obj)
{
// Your operation here
}
}
I removed the word "this" of the parameter of the method.
I'm guessing this relates to your previous list question; if so, the example I provided is an extension method, and would be:
public static class LinkedListUtils { // name doesn't matter, but must be
// static and non-generic
public static IEnumerable<T> Reverse<T>(this LinkedList<T> list) {...}
}
This utility class does not need to be the same as the consuming class, but extension methods is how it is possible to use as list.Reverse()
If you don't want it as an extension method, you can just make it a local static method - just take away the "this" from the firstparameter:
public static IEnumerable<T> Reverse<T>(LinkedList<T> list) {...}
and use as:
foreach(var val in Reverse(list)) {...}
The following points need to be considered when creating an extension method:
The class which defines an extension method must be non-generic and static
Every extension method must be a static method
The first parameter of the extension method should use the this keyword.
How about posting your code? Extension methods are declared by preceding the first parameter of a static method with this. Since you don't won't to use an extension method, I suspect you accidentally started a parameter list with this.
Look for something like:
void Method(this SomeType name)
{
}
This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 1 year ago.
Can extension methods be applied to the class?
For example, extend DateTime to include a Tomorrow() method that could be invoked like:
DateTime.Tomorrow();
I know I can use
static DateTime Tomorrow(this Datetime value) { //... }
Or
public static MyClass {
public static Tomorrow() { //... }
}
for a similar result, but how can I extend DateTime so that I could invoke DateTime.Tomorrow?
Use an extension method.
Ex:
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
Usage:
DateTime.Now.Tomorrow();
or
AnyObjectOfTypeDateTime.Tomorrow();
You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appear to be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.
There is nothing stopping you from creating your own static helper method like this:
static class DateTimeHelper
{
public static DateTime Tomorrow
{
get { return DateTime.Now.AddDays(1); }
}
}
Which you would use like this:
DateTime tomorrow = DateTimeHelper.Tomorrow;
Extension methods are syntactic sugar for making static methods whose first parameter is an instance of type T look as if they were an instance method on T.
As such the benefit is largely lost where you to make 'static extension methods' since they would serve to confuse the reader of the code even more than an extension method (since they appear to be fully qualified but are not actually defined in that class) for no syntactical gain (being able to chain calls in a fluent style within Linq for example).
Since you would have to bring the extensions into scope with a using anyway I would argue that it is simpler and safer to create:
public static class DateTimeUtils
{
public static DateTime Tomorrow { get { ... } }
}
And then use this in your code via:
WriteLine("{0}", DateTimeUtils.Tomorrow)
The closest I can get to the answer is by adding an extension method into a System.Type object. Not pretty, but still interesting.
public static class Foo
{
public static void Bar()
{
var now = DateTime.Now;
var tomorrow = typeof(DateTime).Tomorrow();
}
public static DateTime Tomorrow(this System.Type type)
{
if (type == typeof(DateTime)) {
return DateTime.Now.AddDays(1);
} else {
throw new InvalidOperationException();
}
}
}
Otherwise, IMO Andrew and ShuggyCoUk has a better implementation.
I would do the same as Kumu
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
but call it like this new DateTime().Tomorrow();
Think it makes more seens than DateTime.Now.Tomorrow();
They provide the capability to extend existing types by adding new methods with no modifications necessary to the type. Calling methods from objects of the extended type within an application using instance method syntax is known as ‘‘extending’’ methods. Extension methods are not instance members on the type.
The key point to remember is that extension methods, defined as static methods, are in scope only when the namespace is explicitly imported into your application source code via the using directive. Even though extension methods are defined as static methods, they are still called using instance syntax.
Check the full example here
http://www.dotnetreaders.com/articles/Extension_methods_in_C-sharp.net,Methods_in_C_-sharp/201
Example:
class Extension
{
static void Main(string[] args)
{
string s = "sudhakar";
Console.WriteLine(s.GetWordCount());
Console.ReadLine();
}
}
public static class MyMathExtension
{
public static int GetWordCount(this System.String mystring)
{
return mystring.Length;
}
}
I was looking for something similar - a list of constraints on classes that provide Extension Methods. Seems tough to find a concise list so here goes:
You can't have any private or protected anything - fields, methods, etc.
It must be a static class, as in public static class....
Only methods can be in the class, and they must all be public static.
You can't have conventional static methods - ones that don't include a this argument aren't allowed.
All methods must begin:
public static ReturnType MethodName(this ClassName _this, ...)
So the first argument is always the this reference.
There is an implicit problem this creates - if you add methods that require a lock of any sort, you can't really provide it at the class level. Typically you'd provide a private instance-level lock, but it's not possible to add any private fields, leaving you with some very awkward options, like providing it as a public static on some outside class, etc. Gets dicey. Signs the C# language had kind of a bad turn in the design for these.
The workaround is to use your Extension Method class as just a Facade to a regular class, and all the static methods in your Extension class just call the real class, probably using a Singleton.
Unfortunately, you can't do that. I believe it would be useful, though. It is more natural to type:
DateTime.Tomorrow
than:
DateTimeUtil.Tomorrow
With a Util class, you have to check for the existence of a static method in two different classes, instead of one.
We have improved our answer with detail explanation.Now it's more easy to understand about extension method
Extension method: It is a mechanism through which we can extend the behavior of existing class without using the sub classing or modifying or recompiling the original class or struct.
We can extend our custom classes ,.net framework classes etc.
Extension method is actually a special kind of static method that is defined in the static class.
As DateTime class is already taken above and hence we have not taken this class for the explanation.
Below is the example
//This is a existing Calculator class which have only one method(Add)
public class Calculator
{
public double Add(double num1, double num2)
{
return num1 + num2;
}
}
// Below is the extension class which have one extension method.
public static class Extension
{
// It is extension method and it's first parameter is a calculator class.It's behavior is going to extend.
public static double Division(this Calculator cal, double num1,double num2){
return num1 / num2;
}
}
// We have tested the extension method below.
class Program
{
static void Main(string[] args)
{
Calculator cal = new Calculator();
double add=cal.Add(10, 10);
// It is a extension method in Calculator class.
double add=cal.Division(100, 10)
}
}