C# - Method & Loop

    科技2022-08-18  94

    Methods

    Method Declaration:

    the method nameparameter typesparameter orderparameter namesreturn typeoptional modifiers //y and z are optional parameters. static int AddSomeNumbers(int x, int y = 3, int z = 2) { return x + y + z; }

    Methods that do not return a value have a void return type

    //using x and y inside the method is fine. static void DeclareAndPrintVars(int x) { int y = 3; Console.WriteLine(x + y) }

    Return Keyword: when return is invoked, the current method terminates and control is returned to where the method was originally called. The value that is returned by the method must match the method’s return type, which is specified in the method declaration.

    Out Parameters: return can only return one value. When multiple values are needed, out parameters an be used.

    Expression-Bodied Methods

    static int Add(int x, int y) => x + y;

    Lambda Expressions

    Array.Exists(numbers, (int n) => {return n == 10:}); Array.Exists(numbers, n => n!=7);

    Arrays

    The new keyword is needed when instantiating a new array to assign to the variable, as well as the array length in the square brackets.

    int[] numbers = {3, 14, 59}; string[] characters = new string[] {"a","b","c"}; //Declare an array of lenth 8 without setting the values string[] stringArray = new string[8]; //Declare array and set its values to 3,4,5 int[] intArray = new int[]{3, 4, 5};

    For Loops

    for (int i = 1; i <= 10; i++){ Console.WriteLine(i); }

    For Each Loop

    string[] states = {"a","b","c","d"}; foreach (string state in states) { Console.WriteLine(state); }

    While Loop

    While (guess != "dog") { Console.WriteLine("Make a guess:"); guess = Console.ReadLine(); }

    Do While Loop

    do { DoStuff(); } while (boolCondition);

    Infinite Loop

    while (true) { }

    Jump Statements

    while (true) { Console.WriteLine("This prints once."); //A break statement immediately terminates the loop that contains it. break; } for (int i = 1; i <= 10; i++) { if(i == 7) { //A continue statement skips the rest of the loop and starts another iteration from the start. continue; } Console.WriteLine(i); } static int WeirdReturnOne() { while (true) { //Since return exists the method, the loop is also terminated. Control returns to the method's caller. return 1; } }
    Processed: 0.021, SQL: 9