What's a static method in C#?
A static
function, unlike a regular (instance) function, is not associated with an instance of the class.
A static
class is a class which can only contain static
members, and therefore cannot be instantiated.
For example:
class SomeClass {
public int InstanceMethod() { return 1; }
public static int StaticMethod() { return 42; }
}
In order to call InstanceMethod
, you need an instance of the class:
SomeClass instance = new SomeClass();
instance.InstanceMethod(); //Fine
instance.StaticMethod(); //Won't compile
SomeClass.InstanceMethod(); //Won't compile
SomeClass.StaticMethod(); //Fine
What's the meaning of making a method static? -For dummies
You use non-static classes or object oriented classes, if you want to maintain a state.
When you use static classes, there isn't any state.
For example:
class HelloWorld
{
public string Name {get;set;}
public void SayHello()
{
Console.WriteLine(Name + " hello!");
}
public void SayHi()
{
Console.WriteLine(Name + " hi!");
}
}
You would use the above like this:
HellowWorld obj = new HelloWorld();
obj.Name = "John";
obj.SayHi();
obj.SayHello();
If that was a static class:
static class HelloWorld
{
public static void SayHello(string Name)
{
Console.WriteLine(Name + " hello!");
}
public static void SayHi(string Name)
{
Console.WriteLine(Name + " hi!");
}
}
You would call the above like this:
HelloWorld.SayHello("John");
HelloWorld.SayHi("John");
As you can see, you are repeating yourself.
So it all depends on how you want the class to behave. If you want do and forget, then static class is your friend. If you don't want it to forget something, then use Objects
difference between static variables and static methods
Your question was:
my question now is, if i use a static method, is the return value of
that method shared for all users aswell? or is that always a "unique"
value per user ?
And the answer is, it depends. Using your example:
public class TestClass
{
public static string returnString(string msg)
{
return msg;
}
}
In this case, 5 different users would (most likely) pass in 5 different strings to the static method. Therefore they would get back five differents strings. So for this case:
string value = TestClass.returnString(TextBox1.Text);
each user would get back whatever they had typed into their own TextBox. If, on the other hand the code was this:
string value = TestClass.returnString(testValue);
They would all get back what happened to be in the static string at the time of the return.
So the rule to keep in mind is:
- If the method uses static member variables, there is a risk of different users affecting each other's results. This is true regradless of whether the method is static or not.
- If the method uses only call parameters and local variables, and the call parameters are not themselves pointing to statisc member variables, calls from different users will not affect each other.
When should I write Static Methods?
It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.
EDIT: From stevemegson in the comments
A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.
What is the difference between public static, public and static method?
public
by itself means this is an instance-based member that is accessible to external callers (those with access to the type itself).
static
by itself means the member is not instance-based: you can call it without needing any particular instance (or even any instance at all); without an accessibility qualifier, non-public is assumed - so the member will not be accessible to external callers.
public static
is a static
method that is accessible to external callers.
Memory usage is identical in both cases: any variables declared in the method are scoped to the method-call itself (as an implementation detail: via the stack; also: I'm assuming no "captured variables", and no async
or yield
usage),
Nothing in this is specific to ASP.NET / MVC. However, "action" methods on controllers are, IIRC, expected to be public / instance, so with the public
modifier, and without the static
modifier.
Basically:
Accessibility:
- none specified: defaults to "private" (or "internal" for outer-classes)
- "private": only available to code inside that type
- "protected": available to code inside that type or sub-types
- "internal": available to code in the same assembly
- "protected internal": either "protected" or (union) "internal"
- "public": available to all callers with access to the type
Static / etc:
- none specified: instance-based; an instance is required, and code has automatic access to instance-members (via
this.
) andstatic
members - "static": no instance is required; code has automatic access to
static
members only
What is the difference between static methods in a Non static class and static methods in a static class?
The only difference is that static methods in a nonstatic class cannot be extension methods.
In other words, this is invalid:
class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}
whereas this is valid:
static class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}
Related Topics
How to Create a Custom Authorizeattribute in ASP.NET Core
How to Get a Consistent Byte Representation of Strings in C# Without Manually Specifying an Encoding
C# Compiler Error: "Not All Code Paths Return a Value"
How to Use Linq to Select Object With Minimum or Maximum Property Value
How to Get the Application'S Path in a .Net Console Application
Send Values from One Form to Another Form
Sending Email Through Gmail Smtp Server With C#
How to Pass Data (And References) Between Scenes in Unity
Pass List of Checkboxes into View and Pull Out Ienumerable
Deserialize Json Object into Dynamic Object Using Json.Net
How to Find the Method That Called the Current Method
The Provider Is Not Compatible With the Version of Oracle Client
How to Cancel Task Await After a Timeout Period
Recursion, Parsing Xml File With Attributes into Treeview C#