Static methods and non-static methods in C#

WBOY
Release: 2023-09-04 14:17:08
forward
1083 people have browsed it

C# 中的静态方法与非静态方法

Declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created.

A static class cannot be instantiated and can only contain static members.

Static methods is set using static keyword −

public static int getNum() {
   return num;
}
Copy after login

The following example demonstrates the use of static and non-static methods−

Example

using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }

      public static int getNum() {
         return num;
      }
   }

   class StaticTester {
      static void Main(string[] args) {
         StaticVar s = new StaticVar();

         s.count();
         s.count();
         s.count();
         s.count();
         s.count();
         s.count();

         Console.WriteLine("Variable num: {0}", StaticVar.getNum());
         Console.ReadKey();
      }
   }
}
Copy after login

The above is the detailed content of Static methods and non-static methods in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!