C Sharp/Methods

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Home

Basics
Home
introduction
Overview
Statements
Data Types
Variables
Operators
Flow Control
Variables II
Functions
C# - Classes and Objects I

Dates and Times
Conversions

Advanced
Classes II
Inheritance
GUI
Namespaces
Exceptions
Threads
ADO.NET
Generics

Contents

[edit] C# Methods

C# methods are very similar to functions. Functions can be accessed without an object being declared. A method MUST be accessed via the object it belongs to. A function does not need an object to be accessed, it can be accessed directly from with the Main() block.


Just like functions, methods can accept values and return values. C# Methods must be declared in the class definition like the code below.

public void MyMethod()

If you want the method to be accessible via an object give it public access, but if you want it only accessible in the class itself make it private. There is another access-modifier and it is called protected. We will discuss the protected access-modifier later in this tutorial. here is an example of how to declare a method.


[edit] Call Public C# Methods

using System;
class Program
{
    public class MyClass        //Declare a class
    {
        public void MyMethod()  //Declare a method
        {
            Console.WriteLine("In MyMethod");
        }
 
    }
    static void Main()
    {
        MyClass MyObject = new MyClass();
        MyObject.MyMethod();    //Call method
        Console.Read();
    }
}

Output:

In MyMethod


MyMethod simply prints In MyMethod. Copy and paste this code in your compiler and run it.

[edit] Call Private C# Methods

Example 2: Methods with a private access-modifier

using System;
class Program
{
    public class MyClass        //Declare a class
    {
        public void MySecondMethod()  //public method
        {
            MyMethod();
        }
 
        private void MyMethod()  //private method
        {
            Console.WriteLine("In MyMethod");
        }
    }
    static void Main()
    {
        MyClass ClassObject = new MyClass();
        ClassObject.MySecondMethod();
 
        Console.Read();
    }
}


Output:

In MyMethod


MyMethod can only be accessed within the class itself. It can not be accessed in the Main() block.


[edit] Return Values from C# Method

Returning values from a method is done the same way in returning values from a function. here is a short example:


using System;
class Program
{
    public class MyClass
    {
        public string MyMethod()
        {
            return "Return this string literal";
        }
    }
    static void Main()
    {
        MyClass ClassObject = new MyClass();
        Console.WriteLine(ClassObject.MyMethod());
        Console.Read();
    }
}


Output:

Return this string literal


MyMethod simply returns a string then ends.