The concept of static methods in C#
In C#, adding the "static" keyword before a method indicates that it is a static method, which has unique characteristics compared to ordinary (instance) methods.
Understanding static methods
Static methods are not associated with any specific instance of a class. Instead, they are called using the class name and require no instantiation. As shown below:
<code class="language-c#">public static void DoSomething() { // ... }</code>
To call this static method, just use the class name followed by the method name:
<code class="language-c#">SomeClass.DoSomething();</code>
Static class
Interestingly, C# also allows you to define static classes. A static class is a class that contains only static members and prohibits instantiation:
<code class="language-c#">public static class SomeClass { public static int StaticMethod() { return 42; } }</code>
As you can see, static classes cannot be instantiated and can only contain static methods and fields.
Usage and difference
The choice between static methods and instance methods depends on the specific use case.
Example
Consider the following code:
<code class="language-c#">public class SomeClass { public int InstanceMethod() { return 1; } public static int StaticMethod() { return 42; } }</code>
To call InstanceMethod, you need an instance of SomeClass:
<code class="language-c#"> SomeClass instance = new SomeClass(); instance.InstanceMethod(); // 编译并运行</code>
Static methods can be called directly using the class name:
<code class="language-c#"> SomeClass.StaticMethod(); // 编译并运行</code>
Understanding the concepts of static methods and static classes is crucial to effectively designing classes in C#.
The above is the detailed content of What distinguishes static methods from instance methods in C#?. For more information, please follow other related articles on the PHP Chinese website!