How to define custom method in C#?

王林
Release: 2023-09-15 18:17:06
forward
1007 people have browsed it

How to define custom method in C#?

在C#中定义自定义方法,使用以下语法 −

<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body
}
Copy after login

The following are the various elements of a method −

  • Access Specifier − This determines the visibility of a variable or a method from another class.

  • Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.

  • Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.

  • Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

  • Method body − This contains the set of instructions needed to complete the required activity.

Let us see an example −

Example

 Live Demo

using System;

namespace Demo {
   class NumberManipulator {
      public int FindMax(int num1, int num2) {
         /* local variable declaration */
         int result;

         if (num1 > num2)
         result = num1;
         else
         result = num2;
         return result;
      }

      static void Main(string[] args) {
         /* local variable definition */
         int a = 90;
         int b = 15;
         int ret;
         NumberManipulator n = new NumberManipulator();

         //calling the FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("Max value is : {0}", ret );
         Console.ReadLine();
      }
   }
}
Copy after login

输出

Max value is : 90
Copy after login

The above is the detailed content of How to define custom method 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!