Saturday, December 17, 2016

Part 11: C# Tutorial – Methods in C#

We will cover following points in this article

1. Why methods
2. Method Signature
3. Difference between static and instance methods


     Why Methods

1. Methods are also called as functions.
2. Method is a code block that contains a series of statements and used to define the
    behavior of a class.
3. Methods are extremely useful because they allow you to separate your logic into 
   different units. You can pass information to methods, have it perform one or more 
   statements, and retrieve a return value. 
4. Methods make application maintenance easier. 

Methods Signature 

< attributes> 
<accessmodifiers> <return-type> <method-name> (<parameters>) 
    //method body 
<access modifiers> - public, private, protected, internal, protected internal 
<return-type>          - void or any valid data type 
<method-name>     - can be any meaningful name except reserved keyword <parameters>         - are optional 

Static vs Instance methods 

1. Static methods are declared using static modifier. Static methods are invoked using 
    the class name. 
2.  Instance methods are declared without using the static modifier. Instance methods 
     are invoked using the instance of the class. 
3. A static method cannot access non-static class level members
4. Instance methods can access static fields. 
5. If a method is declared as static then only one definition of the static method exists in 
    the memory. Multiple instances/objects of a single class can invoke only one       
    definition of the static methods but each objects will have its own separate instance 

No comments :

Post a Comment