C# a quickie on Methods

Methods in C# are a block of code that is defined by a certain behavior. For example: You could have a method – as used in previous post – AddGrade()

public void AddGrade(int grade)
{
Do This Block of Code
}

The methods name is AddGrade which represents what the block of code inside of it does well. Every Method has a return type, the void above in AddGrade() says that no value is returned – the return type if not void would be denoted by using the return keyword at the end of the block of code. Parameters are also accepted by methods as indicated inside the parenthesis. The AddGrade() method above accepts the parameter of int grade meaning that it’ll accept an integer value (which will be probably something between 0 -100 since it’s named grade) once it’s called in the program aVariable.AddGrade(91);

The following is an example of creating a method and then executing it in main(). The method accepts a parameter called value and then uses the BitConverter built into .NET to get the bytes of the value.

07062014_BitConverterMethod

Something to be aware of is the way that the compiler will deal with methods of the same name. You can have multiple methods of the same name so long as the parameters are different. For example, you could have WriteAsBytes(int value){} as well as a WriteAsBytes(string value){} and even a WriteAsBytes(float value){}. This is called method overloading. This can be useful because you may have different types of variables that need to run through the method and you don’t have to change the name of the method to accommodate for the different type.

The following example displays how methods have the ability to deal with multiple values passes into it using the params keyword. The method named ParameterTest is saying that it’s able to take multiple string values into an array named names.

07072014_paramsMethod

 

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s