C# Methods

C# Code Snippets Methods


In this code snippet, we will learn about methods in C#.

A method is basically a code block with a name. It can have input parameters to pass data into the code block and it can have a return type to return data out of the code block. A method can be called by writing its name followed by a set of parentheses. 

Methods can be designated as static meaning you don’t have to make an instance of the method’s class to use it. They also have an access modifier(public, private, …) which determines who that method can be called or invoked by.

Methods allow us to break code up into smaller code blocks that only perform one or a couple functions. Very importantly methods allow us to reuse code and thus make it easier to understand and maintain. For example, if we have to fix a bug or add a feature we only have to do it once in the method.

Let’s see how to implement and use a method in the code below.


using System;

namespace Methods
    class Program
        static void Main(string[] args)
            //A method is called by writing its name followned by a set of parentheses.

            //This method will return a value.

            //This method takes a string as an input parameter.
            MyThirdMethod("From MyThird Method");


        //This method is of type void and doesn't return any values.
        public static void MyMethod()
            Console.WriteLine("From MyMethod.");

        //This method is of type string and returns a string.
        public static string MySecondMethod()
            return "From MySecondMethod.";

        //This method has an input parameter.
        public static void MyThirdMethod(string text)

Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger