C Sharp/Functions

Lesson Goals
This lesson will focus on functions in the flow of programming in C# via the console. At the end of this lesson you should be able to:
 * Understand the OOPS point of view regarding the functions.
 * Understand the basic construct of functions.
 * Explain the different scope and use of functions.
 * Understand the relation between funcitons and other C# programming elements.
 * Create different types of functions.

What is a Function?
This is the smallest section of code in functional programming constructs in C# 3.0. Fuctions are very important sections from OOPS standpoint. In more simpler terms, a function encapsulates a block of code that can be called from other parts of the program. introduction of function increases code reusability. Literally you can tag a particular section of code with a name (funciton name) and just call that name from anywhere of your program. In C# a funciton may or may not have a return type. Functions more often are called as Methods. A funciton must be contained in a class. The basic structure of a funciton is as follows, -  { ... } Conversly to call a function you simply call it by its name with parameters, if any, within paranthesis as follows, - DoSomething;

Passing Parameters in Function
The input parameters can be of two types, - If parameters are passed as value type then a new copy of it will be created before passing to the function. Whereas, for reference types only the addresses of the parameters are passed to the function. Meaning, for a value type parameter if the function changes the parameter value then the original variable does not get changed; whereas in case of reference type once the value gets changed in function then the original variable's value gets changed. Here are two examples,-
 * Value type
 * Reference type

(1) Value Type Function  Output  Your birth year is 1980 if your age is 30 (2) Reference Type Function  Output  Your birth year is 1980 if your age is 1980 Notice that in both the code, on line number 19 we are updating the parameter value with the calculated value. In value type example, it is not affecting the variable. But in reference type it is changing the variable value as well. Also for reference type parameter you must use the keyword ref while refereing to a parameter (Second line of output).

N.B. - In both the example we can see two keywords prefixed the function BirthYear, private and static. Private is an access-modifier and static is a keyword that specifies that the function is directly accessible from anywhere in the code. There are many other access-modifiers in C#. These define who can access that function or method. Here is a comprehensive list of them, -

Output Parameters
As you already learned that functions has a return type and that is the output for a function. What if you need to have multiple outputs?

In the parameters list if you provide out keyword in front of a parameter then that becomes output parameter. And you can add as many out parameters. Here is the structure, -  void (ref   Output 

When you are providing both the inputs,- Enter your taxable sum... 1000 Enter your tax rate... 10.2 Your Tax amount is : 102 When you are providing only taxableAmt,- Enter your taxable sum... 1000 Enter your tax rate...

Your Tax amount is : 83.3

(2) Different datatypes of parameters  Output 

When both the inputs are integers,- Enter first Value 12 Enter second Value 23 The summation is = 35 When both the inputs are strings, - Enter first Value Wiki Enter second Value versity The concatenation is : Wikiversity When data is not correct,- Enter first Value 12 Enter second Value Wikipedia Type mismatch! Operation aborted! N.B. - C# determines which function to call based upon the method's signature. If you are defining two methods with the same name and the same number and type of passed arguments, you would get a compile-time error. That is why Overloading is an example of compile-time polymorphism.

Run-time Polymorphism (Method Overriding)
In many occasions you might face a situation where you need to modify a function of a parent class in a derived or child class. To do this .NET provides us the functionality called Function Overriding. This is more frequently used for the implementation of abstruct classes and interfaces. Function Overriding requires us to take note of the following keywords, - Remember: For overriding only two access-modifiers are allowed, public or internal and both the methods in parent as well as child should have that same.
 * virtual - Virtual function must have its implementation in the base class and may optionally be overridden in the child class if some additional functionality is required.
 * abstract - Abstruct function will only have its signature in the base class and must be overridden in the child class.
 * override - Override function is the function in the child class which overrides the same signatured function from its parent.
 * sealed - Only a overridden function can be declared sealed to stop it from any further overriding.

Let's consider the following example, -

 Output  314.2 Abstruct to Override Example. child class Example of Sealed!

Notice that here we have three classes (One class is commented.). the first class ProgramBase is the base class and like all base classes, it is abstruct. It has three methods of which one is abstruct, meaning has only signature. ProgramChild is the child class to the programBase. It is overriding all the methods of the base class and making one of them as sealed. In the main method it is using the methods to give us the output. Notice that Overriding only changes the inner code block of the method in the overrided section, not the signature. Also notice that, in AreaCalc method in ProgramChild we are calling the same method from the base class with the base prefix. One more thing to notice here is that a public method in the base class is a public method in the child class and same for internal. Try to change it and you will get a compile time error. Now to the check the sealed method, just uncomment the ProgramGrandChild class and try to compile. You will get the following error, - 'FunctionApp.ProgramGrandChild.Writer(string)': cannot override inherited member 'FunctionApp.ProgramChild.Writer(string)' because it is sealed

Function Hiding
Function Hiding or Function Shadowing is a variant of overriding. Functions of base classes, by default, are available to the derived class. In case there is a need to not to use the function from base class then you can subscribe to Hiding. This can be achieved using new keyword. Here is how, -  Output  314.2 child class 100 child class 100 base class Here we have two functions AreaCalc and Writer. The first one gets hidden in the child class, whereas, the second function gets overridden in the child. In the Main function we first called both the functions through an instance of the child class and as you can see, it executed the implementation from the child. Till here both overriding and hiding behaved same. Now If we cast the child class instance to the parent class then things bocome interesting. You can see that the overridden function got executed from the child; but the hidden parent class got exposed here. As if you are executing the functions from an instance of the parent class, which is the case for the third scenario.

Meaning, hiding does not follow inheritance rather it just creates a new version. This becomes useful when you want to use your base class throughout your application, not the usual use of child class. N.B.- You can do away with the new keyword and the program will still run; but be ready to get a compiler warning as, - 'FunctionApp.ProgramChild.AreaCalc(double)' hides inherited member 'FunctionApp.ProgramBase.AreaCalc(double)'. Use the new keyword if hiding was intended. Try to reproduce the same with the above code.

Property
This is a special type of function, which mimics the behavior of a variable.   { get;  set;} This is the simplest structure. The get or set is optional. get returns the value and set stores the value. The beauti of it is its simplicity to use.

Further Studies
Following are some high-end stuffs related to functions. Hence, out of scope of this article.
 * Annonymous functions
 * Closures
 * Currying
 * Lambda Expressions

Practice Exercises

 * Create a program for Tower of Hanoi. Take the input of number of rings. Print out the steps.
 * Create a program that would take two inputs and if they are texts then concatenate, but if they are numeric, it will show the summation as result
 * Create a Tax Calculator that will calculate a person's state and federal tax based by taking inputs as follows,-

FirstName

LastName

Address

Taxable amount

And will return the tax amount. (Take predetermined values for various state tax rates).