# C#_W3C # Hello World ``` using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } ``` 1. using System; Using **classes** from the System **namespace** 2. namespace It is a container for **classes** and other **namespaces**. 3. class A container for data and methods Every line of code that runs in C# must be inside a class. 4. Console.WriteLine() 1. **Console** is a class of the **System** namespace, which has a **WriteLine()** method that is used to output/print text. 2. If you omit the using System line, you would have to write System.Console.WriteLine() to print/output text. 3. 會自動換行 4. 可執行數值運算 ``` Console.WriteLine(3 + 3); ``` 5. Write() : 不會自動換行 5. case-sensitive 6. comment ``` // /* */ ``` # Variable + 變數種類 + int + double + char'a' + string"Hello World" + bool : true or false (不用加"") + 使用 1. 字尾 ``` long myNum = 15000000000L; float myNum = 5.75F; double myNum = 19.99D; double精度比較高,建議用double ``` 2. string連接 + ``` string name = "John"; Console.WriteLine("Hello " + name); ``` 3. 宣告 ``` //method 1 int x = 5, y = 6, z = 50; //method 2 int x, y, z; x = y = z = 50; ``` 4. Constants ``` const int myNum = 15; ``` 5. 大小 ``` int 4 bytes -2,147,483,648 to 2,147,483,647 long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 4 bytes Sufficient for storing 6 to 7 decimal digits double 8 bytes Sufficient for storing 15 decimal digits bool 1 bit char 2 bytes string 2 bytes per character ``` 6. Scientific Numbers e or E ``` float f1 = 35e3F; double d1 = 12E4D; ``` 7. C# Type Casting ``` Implicit Casting (automatically) - converting a smaller type to a larger type size char -> int -> long -> float -> double Explicit Casting (manually) - converting a larger type to a smaller size type double -> float -> long -> int -> char int myInt = 9; double myDouble = myInt; // Automatic casting: int to double double myDouble = 9.78; int myInt = (int) myDouble; // Manual casting: double to int ``` 8. Type Conversion (built-in) Methods 兩方向都可以 + Convert.ToBoolean + Convert.ToInt32 (int) + Convert.ToInt64 (long) + Convert.ToDouble + Convert.ToString ``` Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int ``` # User Input 1. 會自動換行 ``` Console.WriteLine("Str"); Console.ReadLine() ``` 2. 不會自動換行 ``` Write("Str") ``` 3. 可執行數值運算 ``` Console.WriteLine(3 + 3); ``` 4. Console.ReadLine() method returns a string,所以要轉態 ``` string userName = Console.ReadLine(); ``` 5. string+int !! ``` Console.WriteLine("Enter your age:"); int age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Your age is: " + age); ``` # Operators + Arithmetic Operators ``` x + y x - y x * y x / y x % y x++ x-- ``` + Assignment Operators ``` x = 5 x += 3 x -= 3 x *= 3 x /= 3 x %= 3 x &= 3 //bit and x |= 3 //bit or x ^= 3 //? x >>= 3 //bit shift right x <<= 3 //bit shift left ``` + Comparison Operators ``` x == y x != y x > y x < y x >= y x <= y ``` + Logical Operators ``` && || ! ``` # Math ``` //直接用 Math.Max(5, 10); Math.Min(5, 10); Math.Sqrt(64); Math.Abs(-4.7); Math.Round(9.99); //四捨五入 ``` # Strings + 宣告 ``` string txt = "Hello World"; ``` + String Length ``` Console.WriteLine("The length of the txt string is: " + txt.Length); ``` + Convert methods ``` Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD" Console.WriteLine(txt.ToLower()); // Outputs "hello world" ``` + String Concatenation ``` string name = firstName + lastName; string name = string.Concat(firstName, lastName); ``` + String Interpolation ``` //可用置換法取代Concatenation string name = $"My full name is: {firstName} {lastName}"; ``` + Access Strings ``` //String indexes start with 0 txt[0] ``` + Find the index position of a specific character ``` txt.IndexOf("e") ``` + Extracts the characters(從指定位置到字尾) ``` int charPos = txt.IndexOf("W"); string newtxt = txt.Substring(charPos); ``` + Special Characters ``` \' \" \\ \n New Line \t Tab \b Backspace ``` # 判斷與迴圈 + If ... Else ``` if (condition1) { // block of code to be executed if condition1 is True } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is True } else { // block of code to be executed if the condition1 is false and condition2 is False } ``` + Short Hand If...Else (Ternary Operator) ``` variable = (condition) ? expressionTrue : expressionFalse; int time = 20; string result = (time < 18) ? "Good day." : "Good evening."; Console.WriteLine(result) ``` + Switch ``` int day = 4; switch (day) { case 6: Console.WriteLine("Today is Saturday."); break; case 7: Console.WriteLine("Today is Sunday."); break; default: Console.WriteLine("Looking forward to the Weekend."); break; } ``` + While Loop ``` While int i = 0; while (i < 5) { Console.WriteLine(i); i++; } ``` + Do/While ``` int i = 0; do { Console.WriteLine(i); i++; } while (i < 5); ``` + For Loop ``` for (int i = 0; i < 5; i++) { Console.WriteLine(i); } for (int i = 0; i <= 10; i = i + 2) { Console.WriteLine(i); } ``` + Foreach Loop ``` string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; foreach (string i in cars) { Console.WriteLine(i); } ``` + Break and Continue + The break statement can also be used to jump out of a loop. + The continue statement breaks one iteration (in the loop) ``` for/if for (int i = 0; i < 10; i++) { if (i == 4) { break; } Console.WriteLine(i); } while/if int i = 0; while (i < 10) { Console.WriteLine(i); i++; if (i == 4) { break; } } ``` # Arrays + Create 1. Create an array of four elements ``` string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; ``` 2. Create an array of four elements, and add values later ``` string[] cars = new string[4]; ``` 3. (少用) Create an array of four elements and add values right away ``` string[] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"}; ``` 4. (少用) Create an array of four elements without specifying the size ``` string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"}; ``` 5. (少用) Declare an array, Add values, using new ``` string[] cars; cars = new string[] {"Volvo", "BMW", "Ford"}; // Add values without using new will cause an error ``` + Access ``` cars[0] ``` + Change an Array Element ``` cars[0] = "Opel"; ``` + Array Length ``` Console.WriteLine(cars.Length); ``` + Loop Through an Array ``` for (int i = 0; i < cars.Length; i++) { Console.WriteLine(cars[i]); } foreach (string i in cars) { Console.WriteLine(i); } ``` + Sort ``` Array.Sort(cars); ``` + Array Method + myNumbers.Max() + myNumbers.Min() + myNumbers.Sum() # Methods (known as functions.) + 範例 ``` namespace MyApplication { class Program { static void MyMethod() { // code to be executed Console.WriteLine("I just got executed!"); } static void Main(string[] args) { MyMethod(); } } } ``` 1. MyMethod() is the name of the method,用大寫開頭比較容易辨識 2. **static** means that the **method** belongs to the Program class and not an **object** of the Program class. 3. void = no return value 4. Call a Method ``` MyMethod(); ``` + Method Parameters ``` static void MyMethod(string fname) { Console.WriteLine(fname + " Refsnes"); } static void Main(string[] args) { MyMethod("Liam"); } ``` + Default Parameter Value (optional parameter) ``` static void MyMethod(string country = "Norway") { Console.WriteLine(country); } static void Main(string[] args) { MyMethod("India"); MyMethod(); } ``` + Multiple Parameters ``` //數量跟順序要照定義 static void MyMethod(string fname, int age) { Console.WriteLine(fname + " is " + age); } static void Main(string[] args) { MyMethod("Liam", 5); } ``` + Multiple Parameters (Named Arguments) ``` key: value (可不照順序pass參數) static void MyMethod(string child1, string child2, string child3) { Console.WriteLine("The youngest child is: " + child3); } static void Main(string[] args) { MyMethod(child3: "John", child1: "Liam", child2: "Liam"); } ``` + Return Values ``` static int MyMethod(int x, int y) { return x + y; } static void Main(string[] args) { int z = MyMethod(5, 3); Console.WriteLine(z); } ``` + Method Overloading ``` same name with different parameters static int PlusMethod(int x, int y) { return x + y; } static double PlusMethod(double x, double y) { return x + y; } static void Main(string[] args) { int myNum1 = PlusMethod(8, 5); double myNum2 = PlusMethod(4.3, 6.26); Console.WriteLine("Int: " + myNum1); Console.WriteLine("Double: " + myNum2); } ``` # Classes and Objects + Create a Class ``` //首字可用大寫區分 class Car { string color = "red"; } ``` + Create Multiple Objects in same class ``` class Car { string color = "red"; static void Main(string[] args) { Car myObj1 = new Car(); Car myObj2 = new Car(); Console.WriteLine(myObj1.color); Console.WriteLine(myObj2.color); } } ``` + Using Multiple Classes (create in different classes) 1. create an object of a class and access it in another class 2. better organization of classes 3. notice the **public** keyword 4. 在兩個.cs檔(class)間,field前要加public(access modifier),讓fields of Car可以被其他的class(Program)存取 ``` //prog2.cs class Car { public string color = "red"; } //prog.cs class Program { static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); } } ``` + Class Members (field & method) ``` class Car { int maxSpeed; // field public void fullThrottle() // method (public) { Console.WriteLine("The car is going as fast as it can!"); } static void Main(string[] args) { Car myObj = new Car(); myObj.maxSpeed = 200; Console.WriteLine(myObj.maxSpeed); myObj.fullThrottle(); // Call the method } } ``` + By default, all members of a class are private if you don't specify an access modifier + Method比較 + public methods can only be accessed by objects.(要新建物件) + static method can be accessed without creating an object of the class + Constructors 1. special method that is used to initialize objects 2. name must match the class name 3. cannot have a return type 4. the constructor is called when the object is created. ``` class Car { public string model; // Create a field // Create a class constructor public Car() { model = "Mustang"; // Set the initial value for model } static void Main(string[] args) { Car Ford = new Car(); Console.WriteLine(Ford.model); } } ``` 5. Constructor Parameters 不用一個一個field慢慢指定,可以像method一次將參數丟入(Save Time) ``` class Car { public string model; // Create a class constructor with a parameter public Car(string modelName) { model = modelName; } static void Main(string[] args) { Car Ford = new Car("Mustang"); Console.WriteLine(Ford.model); } } ``` 6. constructors can be overloaded 7. Access Modifiers + public : The code is accessible for all classes + private : The code is only accessible within the same class + protected : The code is accessible within the same class, or in a class that is **inherited** from that class. + internal : The code is only accessible within its own **assembly**, but not from another assembly. + two combinations: + protected internal + private protected. + 比較 + private field 可以在自己class中的Main建立後讀取,但不能在另外一個class(Program)中的Main建立後讀取 + public 兩個都可以 + By default, all members of a class are private 8. Properties (Get and Set) & Encapsulation + Encapsulation : to make sure that "sensitive" data is hidden from users by declare **fields** as private + Properties : private field + public get/set method (to access and update the value of a private field) ``` class Person { private string name; // field public string Name // property { get { return name; } // get method set { name = value; } // set method } } class Program { static void Main(string[] args) { Person myObj = new Person(); myObj.Name = "Liam"; Console.WriteLine(myObj.Name); } } ``` + Automatic Properties (Short Hand) ``` class Person { public string Name // Automatic property { get; set; } } ``` + read-only (get method only), or write-only (set method only) 9. Inheritance (Derived and Base Class) + for code reusability: ``` class Vehicle // Vehicle : base class (parent) { public string brand = "Ford"; // Vehicle field public void honk() // Vehicle method { Console.WriteLine("Tuut, tuut!"); } } class Car : Vehicle // Car : derived class (child) { public string modelName = "Mustang"; // Car field } class Program { static void Main(string[] args) { // Create a myCar object Car myCar = new Car(); myCar.honk(); //From the Vehicle class // the value of the brand field (from the Vehicle class) // the value of the modelName (from the Car class) Console.WriteLine(myCar.brand + " " + myCar.modelName); } } ``` 10. The sealed Keyword + If you don't want other classes to inherit from a class ``` sealed class Vehicle { ... } ``` 11. Polymorphism(virtual & override) + 多個繼承(Polymorphism)並可改寫(Overriding)原始method + 沒有用virtual & override,子class的method會被父class的method蓋過,等於定義無用 ``` class Animal // Base class (parent) { public void animalSound() { Console.WriteLine("The animal makes a sound"); } } class Pig : Animal // Derived class (child) { public void animalSound() { Console.WriteLine("The pig says: wee wee"); } } class Dog : Animal // Derived class (child) { public void animalSound() { Console.WriteLine("The dog says: bow wow"); } } class Program { static void Main(string[] args) { Animal myAnimal = new Animal(); // Create a Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); } } ``` + 用virtual & override,子類別可獨立定義method + 沒改寫的,會以父method呈現 ``` class Animal // Base class (parent) { public virtual void animalSound() { Console.WriteLine("The animal makes a sound"); } } class Pig : Animal // Derived class (child) { public override void animalSound() { Console.WriteLine("The pig says: wee wee"); } } //..... ``` 12. Abstraction + To achieve security + Abstract class : 先繼承產生子glass,才能用子glass建立物件 + Abstract method : 在abstract class中使用, 沒有body ,body在子glass設定 ``` abstract class Animal { // Abstract method (does not have a body) public abstract void animalSound(); // Regular method public void sleep() { Console.WriteLine("Zzz"); } } //NG Animal myObj = new Animal(); //不能建立物件 //先繼承才能建立物件 class Pig : Animal { public override void animalSound() { // The body of animalSound() is provided here Console.WriteLine("The pig says: wee wee"); } } class Program { static void Main(string[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); // Call the abstract method myPig.sleep(); // Call the regular method } } ``` # Interface 1. 另一個達成Abstraction的方法 2. To achieve security 3. can only contain abstract methods and properties (with empty bodies), but not fields. 4. By default, members of an interface are abstract and public 5. On implementation of an interface, you must override **all of its methods** 6. interface沒有建構函式(因為不能用他產生物件) ``` // Interface interface IAnimal { void animalSound(); // interface method (does not have a body) } // Pig **implements** the IAnimal interface class Pig : IAnimal { public void animalSound() { // The body of interface method is provided here Console.WriteLine("The pig says: wee wee"); } } class Program { static void Main(string[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); } } ``` 8. Multiple Interfaces + C#沒有 "multiple inheritance"(多個父母),但可以 implement multiple interfaces ``` interface IFirstInterface { void myMethod(); // interface method } interface ISecondInterface { void myOtherMethod(); // interface method } // Implement multiple interfaces class DemoClass : IFirstInterface, ISecondInterface { public void myMethod() { Console.WriteLine("Some text.."); } public void myOtherMethod() { Console.WriteLine("Some other text..."); } } class Program { static void Main(string[] args) { DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); } } ``` # Enum + a special "class" that represents a group of constants + catch letter ``` class Program { enum Level { Low, Medium, High } static void Main(string[] args) { Level myVar = Level.Medium; Console.WriteLine(myVar); } } ``` + catch default value ``` enum Months { January, // 0 February, // 1 March, // 2 April, // 3 May, // 4 June, // 5 July // 6 } static void Main(string[] args) { int myNum = (int) Months.April; Console.WriteLine(myNum); } ``` + change default value ``` enum Months { January, // 0 February, // 1 March=6, // 6 April, // 7 May, // 8 June, // 9 July // 10 } ``` + with switch...case... ``` enum Level { Low, Medium, High } static void Main(string[] args) { Level myVar = Level.Medium; switch(myVar) { case Level.Low: Console.WriteLine("Low level"); break; case Level.Medium: Console.WriteLine("Medium level"); break; case Level.High: Console.WriteLine("High level"); break; } } # Files ``` using System.IO; // include the System.IO namespace // Create a text string string writeText = "Hello World!"; // Create a file and write the content of writeText to it File.WriteAllText("filename.txt", writeText); // Read the contents of the file string readText = File.ReadAllText("filename.txt"); // Output the content Console.WriteLine(readText); ``` + other method ``` https://docs.microsoft.com/en-us/dotnet/api/system.io.file?view=netframework-4.8 ``` + ReadAllText() : Reads the contents of a file + WriteAllText() : Creates a new file and writes the contents to it. If the file already exists, it will be overwritten. + AppendText() : Appends text at the end of an existing file + Copy() : Copies a file + Create() : Creates or overwrites a file + Delete() : Deletes a file + Exists() : Tests whether the file exists + Replace() : Replaces the contents of a file with the contents of another file # Exceptions + Try..Catch ``` try { int[] myNumbers = {1, 2, 3}; Console.WriteLine(myNumbers[10]); Console.WriteLine(myNumbers[10]); } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine("The 'try catch' is finished."); } ``` + The throw keyword + allows you to create a custom error. + ArithmeticException + FileNotFoundException + IndexOutOfRangeException + TimeOutException + etc ``` static void checkAge(int age) { if (age < 18) { throw new ArithmeticException("Access denied "); } else { Console.WriteLine("Access granted"); } } static void Main(string[] args) { checkAge(15); } ```