Object Oriented Programming and C#: Methods

Methods in C# are quite similar to functions in C. A function is something that takes input parameters and returns outputs. The major difference between methods, which are involved with object oriented programming, and functions is that methods are associate with objects. Methods give the programmer a huge advantage in the sense that their code is much easier to read and allows the user to reuse code to avoid repetitions. It is important to note that methods can only be contained within classes and methods declared within methods are not allowed. The method “Main” is included in every program.

The following is the syntax for a method:

method

The return type for “main” is void since it does not return a value. The name of the method and list of parameters are called the “method signature”. The name of the method should contain either a verb or a noun and a verb. An “access modifier” gives the compiler information about how the method can be used, just as with classes. Examples are public, private, etc. The “static” method is a method that does not need to be instantiated.

“Local variables” are variables defined within a method that can only be used within the method. The area of visibility for this variable is from where it is defined to the last bracket of the method body.

Methods can be called from the “main” method or from some other method. In fact, methods can call themselves (this is called recursion). You can also call a method BEFORE it is declared!

A method’s parameters are the inputs necessary to complete whatever task the method needs to achieve. Arrays can be used as parameters if necessary. When declaring a method with parameters, the values in the parentheses are called parameters, but when the method is called, the values actually used are called arguments.

Another important note is that when a variable is passed to a method argument, the value is copied to the parameter for use within the method. However, when a variable is declared within a certain method and then placed as an argument to a method, if the parameter is hardcoded within that method, it will use the hardcoded value but the variable declared will not be effected. Here is an example:

printnum

main

This will print the number 5 (not 3). In the Main() method, however, numberArg is 3.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s