Static keywords in C #

Source: Internet
Author: User
Static variables and static methods

 

  1. Static variable

 

Static variables (class variables) are global variables that can be shared among object instances.

class ABCD{    char data;    static int share_data;}class StaticDemo{    ABCD a,b,c,d;}

The above four objects A, B, C, and D share the static variable pai_data.

The lifetime of static variables does not depend on objects. Other classes can access them without instantiation:

public class StaticVar{    public static int number = 5;}public class OtherClass{    public void Method()    {        int x = StaticVar.number; // here    }}

 

Static Method

Static methods are equivalent to global functions in C language. Other classes call them without instantiation, just like static variables.

We know that global variables can be divided into instance variable and static variable. Likewise, methods can be divided into instance methods and static methods (with the static keyword). When using variables, pay attention to the following rules:

Instance methods can use both instance variables and class variables;
Static methods can only use class variables, but cannot directly use instance variables.

 

  1. When a value is assigned to a static variable, the value of the variable is the value after the last value is assigned to the variable during the program running.
private void TestValue(){    static int num = 1;    num++;}

After the method is called for the first time, the value of num in the memory is 2, and the value after the second call is 3.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.