The difference between static and non-static variables in asp.net

Source: Internet
Author: User
Tags modifier net variables string variable

Static variables:
Static variables are declared with the static modifier
Created when the owning class is loaded
Access through a class
The same static variable for all instances of the owning class is the same value
Non-static variables:
Variables not declared with the static modifier are called non-static variables
Created when a class is instantiated
Access through objects
The same non-static variable for different instances of the same class can be a different value
Example:


[Copy to Clipboard] CODE:

Using System;
Using System.Collections.Generic;
Using System.Text;
Namespace Example01
{
Class Program
{
Class Class1
{
public static String staticstr = "Class";
Public String notstaticstr = "OBJ";
}
static void Main (string[] args)
{
A static variable is accessed through a class, and the same static variable for all instances of the class is the same value
Console.WriteLine ("Class1 ' s Staticstr: {0}", CLASS1.STATICSTR);
Class1 tmpObj1 = new Class1 ();
Tmpobj1.notstaticstr = "TmpObj1";
Class1 tmpObj2 = new Class1 ();
Tmpobj2.notstaticstr = "TmpObj2";
Non-static variables are accessed through objects, and the same non-static variable of different objects can have different values
Console.WriteLine ("TmpObj1 ' s Notstaticstr: {0}", TMPOBJ1.NOTSTATICSTR);
Console.WriteLine ("TmpObj2 ' s Notstaticstr: {0}", TMPOBJ2.NOTSTATICSTR);
Console.ReadLine ();
}
}
}


Results:
Class1 ' s Staticstr:class
TmpObj1 ' s notstaticstr:tmpobj1
TmpObj2 ' s NOTSTATICSTR:TMPOBJ2



Related Article

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.