
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to define methods in C#?
A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main.
When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows −
<Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body }
Here,
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.
The following is an example of methods showing how to find that a string has unique words or not. Here, we have created a C# method CheckUnique() −
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Demo { public bool CheckUnique(string str) { string one = ""; string two = ""; for (int i = 0; i < str.Length; i++) { one = str.Substring(i, 1); for (int j = 0; j < str.Length; j++) { two = str.Substring(j, 1); if ((one == two) && (i != j)) return false; } } return true; } static void Main(string[] args) { Demo d = new Demo(); bool b = d.CheckUnique("amit"); Console.WriteLine(b); Console.ReadKey(); } }
Output
True
- Related Questions & Answers
- How to define custom methods in C#?
- How to define methods for an Object in JavaScript?
- How to define expressions, variables, and methods in JShell in Java 9?
- How to define constants in C++?
- How to define namespaces in C#?
- How to define variables in C#?
- How to define a variable in C++?
- How to define jagged arrays in C#?
- How to define a structure in C#
- How to define param arrays in C#?
- How to define an array in C#?
- How to define character constants in C#?
- How to define multi-dimensional arrays in C/C++?
- How to define dynamic data types in C#
- How to define multi-dimensional arrays in C#?