C # static and non-static classes (instance classes)

Source: Internet
Author: User

1. Static and non-static members can appear in non-static classes

usingSystem;namespaceshuzu{classDom_class { Public stringName ="Zhang San"; Private intAge ;  Public intAge//accessing private members through properties        {            Get{returnAge ;} Set{age =value;} }    }    classAClass {Static voidMain (string[] args) {Dom_class s=NewDom_class (); S.name="ABC"; S.age= the;             Console.WriteLine (S.name);            Console.WriteLine (S.age);        Console.readkey (); }    }}
View Code

2. Static members can only appear in static classes, and object creation is not allowed

usingSystem;namespaceshuzu{Static classAClass {Static inti = the; Static voidMain (string[] args) {i= -;//accessing static MembersConsole.WriteLine (ACLASS.I);//You can also access thisConsole.WriteLine (i);        Console.readkey (); }    }}
View Code

3. Differences on non-static and static member invocations (class name point object name) non-static (object name point member name)

usingSystem;namespaceshuzu{classDom_class { Public Static intShu = -;//access to static members    }    classAClass {Static voidMain (string[] args) {           intg= Dom_class.shu = the;//The class name. Object Name AccessConsole.WriteLine (g);        Console.readkey (); }    }}
View Code
usingSystem;namespaceshuzu{classDom_class { Public stringName ="Zhang San";//access to non-static members        Private intAge ;  Public intAge//accessing private members through properties        {            Get{returnAge ;} Set{age =value;} }    }    classAClass {Static voidMain (string[] args) {Dom_class s=NewDom_class (); S.name="ABC";//by establishing object accessS.age = the;             Console.WriteLine (S.name);            Console.WriteLine (S.age);        Console.readkey (); }    }}
View Code

4. When do I use static classes? Use static classes when used as a tool class

C # static and non-static classes (instance classes)

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.