C# Methods, part 1 - Method Signature
(Page 2 of 6 )
The first issue we will discuss is the method signature. You begin your method declaration with an access modifier, followed by the static keyword (in the case of a static method), then the return data type. If there is no return data type, use the void keyword instead. This is followed by the method name and the parentheses, which may contain parameters.
accessModifier static dataType MethodName(dataType parameterName)
{
statement 1;
statement 2;
statement 3;
return expression or value;
}
Note the use of the return keyword to return a value to the caller. In the case of a void method, you will not be able to return any value from the method.
The next table lists the available access modifiers in C#. I have listed this table before, but I'm listing it again here in case you didn't read the previous articles.
Access Modifier | Description |
| public | States the class member accessible for all the derived classes, classes in other assemblies and for client code. |
| private | The opposite of the public Access Modifier, states that the class member is not accessible for any code including derived classes, so the only code that can access (or manipulate) this member is the declared class. Object Oriented Programming provides data protection using the private (and protected) Access Modifiers. For example, you can declare the salary field inside the Employee class as private and it will not be accessible or visible outside this class declaration, so there's no client code that can modify its value unless you, the programmer, want that. |
| protected | This is an intermediate access level between the public and the private Modifiers. It states that the member is accessible for only derived classes, which gives you the ability to declare fields that are not accessible outside the declared class and any class that derive from it. For example, you can define a class such as ManagerEmployee that derives from and extends the Employee class. |
| internal | This is an interesting Access Modifier that states that the class member is accessible only for the current assembly (we will discuss assemblies later). This means that the member is public for the assembly, but it's not visible outside the assembly. |
So you can write a public method in the following way:
public int GetNumber(int min, int max)
{
System.Random random = new Random();
return random.Next(min, max);
}
This method has two parameters (we will discuss parameters in the second part in detail) that represent the minimum and maximum values that the System.Random class use to generate a random number. The method returns the value that returns from the call to the random.Next method. We will talk more about the GetNumber method soon. Now let's take about the different types of methods.
Next: Instance Methods >>
More C# Articles
More By Michael Youssef