{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9f1c08e0-4c54-4bc8-8168-0ad6df83de56",
   "metadata": {},
   "source": [
    "# Designing Methods"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51f658da",
   "metadata": {},
   "source": "## Method Signature\n\nThe first method you have encountered in C# is the Main method, in which *Main* is\nthe name that you can to refer to this set of statements. A Main method is special\nbecause it is designated as the only entry point of a C# application and therefore\nthe first method to be invoked in a class [^1].\n\nNote that the **Main method** is contained in a **class** (Program), which is a\nstandard arrangement for OOP languages.\nYou define a method by writing the method’s **header** and **body**. The header is\nalso called a **method signature**. [^2] When defining methods, you follow a recipe\n(standard syntax) to specify the **method signatures**. The\nstandard syntax template for method signatures is as follows: [^3]\n\n``` none\n[Access Modifier] [static modifier] [Return Type] MethodName(Parameter List)\n{\n   // Method Body: a set of statements enclosed in curly braces { }\n}\n```\n\nIn this template, the signature include the following parts:\n\n| Signature | Description |\n| --- | --- |\n| Access Level | Optional. This determines visibility of methods between classes, and whether or not it can instantiate new objects. Since our methods in this chapter are limited to this class, we will leave them off for now. |\n| Static modifier | Define the method as a static member method of the class. When not defined as static, it is an instance member. [#f3]_ |\n| Return Type | If the method is returning a value, this indicates what data type it will be. Not all methods return values. Methods that do not return a value have a return type of `void`. |\n| Method Name | The method’s unique `identifier`. This is what you use to call your method. |\n| Parameter List | A parameter is a placeholder for specific data that the method will act upon. Parameters are optional. In these cases, the `()` are still part of the method call, but remain empty. |\n| Method Body | This is where you code your method. Note it is contained between `{}`. |\n\nWith method signatures, you can design methods specifically to your needs. But for now, let us analyze the two methods in class TryMethods below to apply our understanding of signatures:"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3acb2614",
   "metadata": {
    "vscode": {
     "languageId": "csharp"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IST 1551\n",
      "T.Y. Chen\n"
     ]
    }
   ],
   "source": [
    "using System;                          // the using statement\n",
    "\n",
    "#pragma warning disable CS7022\n",
    "\n",
    "class TryMethods                       // class declaration\n",
    "{\n",
    "   // public static void Main(string[] args)     // static modifier, return modifier, and method name\n",
    "   // {                                   // static: can be invoked directly; void, no return to caller\n",
    "   //    MyMethod();                      // method MyMethod (line# 9) is called\n",
    "   // }\n",
    "\n",
    "   public static void MyMethod()       // static modifier, return modifier, and method name\n",
    "   {                                   // static: can be invoked directly; void, no return to caller\n",
    "      Console.WriteLine(\"IST 1551\");   // Method body\n",
    "      Console.WriteLine(\"T.Y. Chen\");  // Method body\n",
    "   }\n",
    "}\n",
    "\n",
    "TryMethods.MyMethod();  // invoking the Main method of TryMethods class\n",
    "\n",
    "#pragma warning restore CS7022"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3ab7ef7",
   "metadata": {},
   "source": [
    "You have probably noticed that you can prepare this code by making the **MyMethod**\n",
    "project folder (`mkdir MyMethod`), then creating the project by running `dotnet new console --use-program-main` (or just do `dotnet new console` then change the code to include\n",
    "the `Main method`). After that, you run `code .` from the terminal to open\n",
    "the project in VS Code and click on Program.cs to edit the source code.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cca85ec",
   "metadata": {},
   "source": "## Method Calls & Returns\n\nIn the preceding code, we add a new method, `MyMethod`, and call it directly from the program body using **top-level statements** — no `Main()` wrapper is needed.\n\nWhen making a method call, you use the method **name** followed by\n**parentheses**. The method header `static void MyMethod()` indicates the return type is `void` and there are no formal parameters, which means you can call it simply by writing `MyMethod();`.\n\nAn important feature of functions/methods is that they can **return** values to their\n**callers**. In the example below, `SquareTheNumber()` is defined with a return type of `int`\nand is called directly from the top-level code, passing a parameter."
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df1bc6ee-7109-4572-b3da-abe31a69c185",
   "metadata": {
    "mystnb": {
     "number_source_lines": true
    },
    "vscode": {
     "languageId": "csharp"
    }
   },
   "outputs": [],
   "source": [
    "static int SquareTheNumber(int num)\n",
    "{\n",
    "    return num * num; // the value to be returned is given by the expression in the return statement.\n",
    "}\n",
    "\n",
    "int digit = 4;\n",
    "int squaredNum = SquareTheNumber(digit);\n",
    "int squaredAndSummed = squaredNum + SquareTheNumber(digit);\n",
    "\n",
    "Console.WriteLine(squaredNum);\n",
    "Console.WriteLine(squaredAndSummed);\n",
    "Console.WriteLine(SquareTheNumber(5));"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "462609ac-4ab1-465f-9726-dcae6ebf67a7",
   "metadata": {},
   "source": [
    "In the preceding code, we see that:\n",
    "\n",
    "- line# 3 uses the `return` keyword to create a return statement to return\n",
    "  the resulted value to the caller.\n",
    "- Line# 6 initializes the value of int variable digit to 4\n",
    "- Line# 7 calls the squaredNum() method with argument digit (4) and save the resulted\n",
    "  return value to int variable squaredNum.\n",
    "- Line# 8 add squaredNum and add it to the return value of the method call with argument value of 5.\n",
    "\n",
    "Since methods can return data, and all data in C# is typed,\n",
    "there must be a type given for the value returned. Note that in the preceding\n",
    "code the method header does not start with `static void`.\n",
    "In place of `void` is `int`. The `void` in method headers\n",
    "mean nothing was returned. The `int` here means that a value *is*\n",
    "returned and its type is `int`.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eca3a48d",
   "metadata": {},
   "source": "## Flow of execution\n\nIn terms of the construct of **sequential processing**, functions/methods\nalter code execution order in several ways: by statements not\nbeing executed as the definition is first read, and then when the\nmethod is called during execution, jumping to the method code,\nand back at the end of the method execution. [^5]\n\nA class can contain multiple methods. It can be tempting to think the\nmethods are executed in the order they appear in the class, but this is\nnot the case. A program always begins at the first statement in the Main\nmethod. Each statement in the main is executed sequentially, one at a\ntime, until you reach a method call. A method call causes the program\nexecution to jump to the first line of the called method.\nEach statement in the called method is then executed in order.\nWhen the called method is done, the program returns to the\nmain method. [^6]\n\nIn other words, the order in which the method definition code blocks does\nnot matter to C#. It is a human choice. One good practice is to show\n`Main` first. This means a human reading in order gets an overview\nof what is happening by looking at Main, but does not know the details\nuntil reading the definitions of other methods.\n"
  },
  {
   "cell_type": "markdown",
   "id": "ea62a477",
   "metadata": {},
   "source": "```{rubric} Footnotes\n```\n\n\n[^1] Note that if you have more than one Main method in you have to use the\n[StartupObject](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/advanced#mainentrypoint-or-startupobject)\ncompiler option to specify which Main method to use as the entry point.\n\n[^2] Note that, in OOP, method signature usually refers the method name and the type of\nits parameters (enclosed in parentheses and separated by commas) while the method\nheader means the whole first line of the method definition. Here we use the\ndefinition from [Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/csharp/methods)\nto make it simple.\n\n[^3] This template and explanation is adopted from <https://education.launchcode.org/intro-to-programming-csharp/chapters/methods/method-signatures.html>\n\n[^4] Main method is required for console and Web apps in .NET.\n\n[^5] <https://education.launchcode.org/intro-to-programming-csharp/chapters/methods/method-signatures.html#method-calls>\n\n[^6] <https://runestone.academy/ns/books/published/csjava/Unit5-Writing-Methods/topic-5-1-writing-methods.html>"
  },
  {
   "cell_type": "markdown",
   "id": "5fcc5a9a",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".NET (C#)",
   "language": "C#",
   "name": ".net-csharp"
  },
  "language_info": {
   "file_extension": ".cs",
   "mimetype": "text/x-csharp",
   "name": "C#",
   "pygments_lexer": "csharp",
   "version": "13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}