This question already has answers here:
Method can be made static, but should it?
(14 answers)
Closed 8 years ago.
Is there any harm or benefit for having instance methods call static methods to do their work?
If your confused by what I mean, take a look at the example code below. StripFormatting is an instance method and static method. If another developer creates an instance of PhoneUtil then all that is needed is for the StripFormatting method to be called on the instance of the object. If a developer decides not to create an instance of PhoneUtil they can call the static method except this method has a parameter for the PhoneNumber.
public string StripFormatting()
{
return PhoneUtil.StripFormatting(this.PhoneNumber);
}
public static string StripFormatting(string psPhoneNumber)
{
string tsPhoneNumber = psPhoneNumber;
Regex toNotDigit = new Regex("\\D+");
tsPhoneNumber = toNotDigit.Replace(tsPhoneNumber, "");
return tsPhoneNumber;
}
Member function or Static methods are chosen based on your software design. There are pros and cons in relation to that design you have chosen.
In general, consider using static methods when that method has no any effect on some type internal state and does not need to store some data inside, in shorts: it's execution only.
In all oher cases conside using instance methods.
Repeat this is a basic idea,as all depends on your design.
For example: looking on the code provided I see that method you wrote can easily be made static.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am making C# console applications in Notepad++ and MonoDevelop with only a .cs file instead of a solution. I compile the code from CMD.
I want to add two classes in my simple "Hacked" program that just simply displays a lot of 0's and 1's. EVERY time I try to make an object reference, I get an error in the compiler saying that I need to make a reference for non-static fields. Making methods static works, but I don't think that every method should be static.
So my question is, how do I make object references without an IDE?
EDIT: I have found the solution by making the variable static. And I knew that when a method was static, it could be accessed from any class without a reference. I was just testing a class reference to learn a little more about C#. But I make the class reference variable static and anything that isn't static in the referenced class works fine. Thank you all for helping me out though as your suggestions and explanations did help me.
Nice to see someone starting so simple. Object references are the same no matter if you are working in VisualStudio, or in a simple text editor.
This is actually an error in your code and not the fact that you are not using an IDE.
I'm assuming you have not gone into object oriented programming too much, and that these are simple, single class programs to help you get started.
In this case, all other methods, fields, etc, are accessed in some way from your public static Main(string[] args) method. Static methods are accessible from all classes, and do not require an object instance. Methods and fields accessed without an instance must be static.
So, in this case, yes, every method does need to be static.
Check out this question, What's a "static method"?
For example, say you create a class called Math, and create a Pow(int x, int power) (power) method (This is part of the .NET framework). You would make this function static because you want ALL classes to be able to access it without creating an instance of the Math class.
int square = Math.Pow(2, 2); //Static method, no instance needed
Now say, you make a class called Book, this class has methods such as GetPagesLeft(). In this case, it is specific to each instance of a "book", and should not be static, because it applies to each instance.
Book book = new Book(); //Create instance
int pagesLeft = book.GetPagesLeft(); //Instance method
Don't be afraid of using static methods, they are there for a reason.
Note, I'm not a professional developer, so some of the terminology I used may not be exactly correct, but I hope it gets the point across.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// instanceMethod(); // Error calling instance method without an instance.
// Won't even compile
Program prg = new Program();
prg.instanceMethod(); // No Error calling instance method from instance
staticMethod(); // No Error calling static method without an instance
}
void instanceMethod()
{
}
static void staticMethod()
{
}
}
}
This question already has answers here:
Use of "this" keyword in formal parameters for static methods in C#
(7 answers)
Closed 9 years ago.
I found a method declared like this:
public static int WordCount(this string str)
{
return str.Length;
}
What's the this keyword in this particular context?
It's an extension method. Extension methods allow you to extend a type. It's great for types like string for which you don't have access to the source code.
With the example you provided, instead of calling
string test = "foo";
var result = StaticClass.WordCount(test);
You could use it as follows:
string test = "foo";
var result = test.WordCount();
Trivia: LINQ is implemented using extension methods, and in fact was the primary reason extension methods were added to the .NET framework.
It makes it an extension method.
What this means is that you can call the method like this:
arg.WordCount();
instead of like this:
Class.WordCount(arg);
It's mainly used for extending types (hence the name) that you can't directly modify the source code of.
This question already has answers here:
"this" in function parameter
(5 answers)
Closed 9 years ago.
I want to understand how extension method works?Can we define extension methods in non static classes?
*
Why do we put extension methods inside static class?
*
According to MSDN,
**Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods
are only in scope when you explicitly import the namespace into your
source code with a using directive.
**
What is the role of this operator here and how does it associates that extension method to that argument?
No, you can't define an extension method on a class that is not static.
The this is syntactic sugar that allows to call your static extension method on an instance. But at the end of the day, an extension method is nothing more than a static method in a static class.
So basically:
var test = myInstance.MyExtensionMethod();
is the same as
var test = MyExtensionClass.MyExtensionMethod(myInstance);
They are 4 requirements for method to be an extension method:
It has to be declared in static class
It has to be static (which actually is always true if the first one is met)
It has to be public
It has to have first parameter marked with this keyword
So you can't define extension method in non-static class.
Whole Extension Method functionality is some kind of syntax sugar. Following extension method declared on MyClass:
// The following extension methods can be accessed by instances of any
// class that is or inherits MyClass.
public static class Extension
{
public static void MethodA(this MyClass myInterface, int i)
{
Console.WriteLine
("Extension.MethodA(this IMyInterface myInterface, int i)");
}
}
can be called in two ways:
var myClassObject = new MyClass();
Extension.MethodA(myClassObject);
Or
myClassObject.MethodA();
However, the second one will be transformed into the first one by compiler anyway.
What is the role of this operator here and how does it associates that
extension method to that argument?
In this context this is not an operator, it is a modifier. It could have been called something else, it has no relation to this object which refers to the current object within a normal method call.
The role of this modifier is to tell the compiler that this is actually an extension method and not a standard static method, so that it will not complain when you call it in a way which looks like an instance method call, although it is not.
No, extension methods have to be in a static class, that's just the rule. It could have been possible to allow extension methods to be defined anywhere, but to make it easier to find them they are not allowed to be buried inside classes with a lot of other code.
The this keyword is used on the first parameter of an extension method to specify that it is an extension method.
(The internal implementation of a regular method also has a reference to the object as a first parameter, so what the compiler does with extension methods is just to add them to the other methods in the class.)
This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 2 years ago.
According to Microsoft, "Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type".
Is there a way to add an extension method that it called as if it was a static method? Or to do something else that has the same effect?
Edit:
By which I mean "called as if it was a static method on the extended class".
Sorry for the ambiguity.
According to Microsoft, "Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type".
Yes, extension methods are static methods. They can all be called in the normal way as static methods, as extension instance methods on the type they "extend", and they can even be called as extension methods on a null reference.
For example:
public static class Extensions {
public static bool IsNullOrEmpty(this string theString) {
return string.IsNullOrEmpty(theString);
}
}
// Code elsewhere.
string test = null;
Console.WriteLine(test.IsNullOrEmpty()); // Valid code.
Console.WriteLine(Extensions.IsNullOrEmpty(test)); // Valid code.
Edit:
Is there a way to add an extension method that it called as if it was a static method?
Do you mean you want to call, for example, string.MyExtensionMethod()? In this case, no, there is no way to do that.
Extension methods are static methods. You don't need to do anything.
The only thing that distinguishes an extension method from any other static method is that it can be called as if it were an instance method in addition to being called normally as a static method.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When do you use the “this” keyword?
If I have the following example:
public class MyClass {
private void MyMethod1()
{
...
}
private void MyMethod2()
{
this.MyMethod1();
...
}
}
In the "MyMethod2" is there a difference in use "this.MyMethod1()" or just "MyMethod1()"? Performance, security, good practice, or whatever? I ask this, because normally I don't use "this" to call methods in the same class, but I get code developed by other people that use it... maybe I'm wrong... or not!
Sorry if looks like a silly question, but I'm "curious" after all. Thank you!
In that specific example there is no difference - it will compile to identical bytecode.
It only makes a difference if there is a local variable or parameter with the same name as the method you want to call, in which case you need to write this to refer to the member and not the local variable.
Not performance, they will compile to the same IL.
The thing with the this keyword is that it you don't have local variables with the same naming as the class members.
private void MyMethod2()
{
Action MyMethod1 = MyMethod2;
MyMethod1(); // recursive call to MyMethod2
this.MyMethod1(); // call to real MyMethod1
}
Other than that some people like it, some does not. Follow the code standard in your team.
There is no difference from an execution standpoint. As you imply, some people use this, some don't.
Use the standard you've decided is correct, unless you are overridden by company standards.