public static void Main() { var gems = Console.ReadLine() .Split(" ", StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); var listOfCommands = new List <string>(); var gemsForRemove = new HashSet <int>(); while (true) { var input = Console.ReadLine(); if (input == "Forge") { break; } if (input.Contains("Exclude")) { listOfCommands.Add(input.Substring(8, input.Length - 8)); } else { while (listOfCommands.Contains(input.Substring(8, input.Length - 8))) { listOfCommands.Remove(input.Substring(8, input.Length - 8)); } } } foreach (var command in listOfCommands) { var condition = command.Split(";", StringSplitOptions.RemoveEmptyEntries)[0]; var value = int.Parse(command.Split(";")[1]); for (int i = 0; i < gems.Count; i++) { if (GetSum(gems, condition, value)(i)) { gemsForRemove.Add(i); } } } foreach (var index in gemsForRemove.OrderByDescending(x => x)) { gems.RemoveAt(index); } Console.WriteLine(string.Join(" ", gems)); }
static void Main(string[] args) { //anonymous method GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); //lambda Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); //lambda with list List <int> numList = new List <int> { 5, 10, 15, 20, 15 }; List <int> oddNums = numList.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.WriteLine(num + ","); } }
static void Main(string[] args) { //Delegate GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); //Invoke Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); List <int> numList = new List <int> { 5, 10, 15, 20, 25 }; List <int> oddNums = numList.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.WriteLine(num); } Console.Read(); }
/// <param name="site">据点</param> /// <param name="type">cct 车贴 /// cdt 单透 /// cpp PPF /// cwg 外购 /// /// bbj 背胶大卷 /// bdt 单透大卷 /// bgz 硅纸 /// bsz 素纸 /// /// yyz 原纸 /// yhg 化工 /// yjs 胶水 /// ymw 膜 外购 /// ymz 膜 自产 /// </param> /// <param name="dayType"> /// a 1-15天 /// b 16-30天 /// c 31-90天 /// d 91-180天 /// e >180 /// f 其他(无条码日期) /// </param> public static GetSum WebMX(string site, string type, string dayType, int pageIndex) { GetSum gs = new GetSum(); gs.web = ""; gs.sum1 = 0; gs.sum2 = 0; string sql_ct = StorAge.GetSql.MXsql(site, type, dayType, pageIndex); DataTable da = StorAge.OracleConfig.queryDataTable(sql_ct); foreach (DataRow dr in da.Rows) { gs.web += "<tr>"; for (int i = 0; i < da.Columns.Count; i++) { if (i == 10 || i == 12 || i == 13) { gs.web += "<td style = \"text-align: right;\">" + String.Format("{0:N2}", dr[i]) + "</td>"; } else { gs.web += "<td>" + dr[i].ToString() + "</td>"; } } gs.sum1 += Convert.ToDouble(dr["INAG008"].ToString()); gs.sum2 += Convert.ToDouble(dr["INAG025"].ToString()); gs.web += "</tr>"; } gs.web += "<tr>"; gs.web += "<td colspan=\"9\">总数量:</td><td colspan=\"2\">" + String.Format("{0:N2}", gs.sum1) + "</td>"; gs.web += "<td colspan=\"2\">参考总数量:</td><td colspan=\"2\">" + String.Format("{0:N2}", gs.sum2) + "</td>"; gs.web += "</tr>"; return(gs); }
static void Main(string[] args) { //语法 // 委托类型 委托变量 = delegate (类型 参数列表){ 方法体 }; //普通匿名委托方法 // GetSum getSum = delegate (int max, int min) // { // int sum = 0; // for (int i = min; i <= max; i++) // { // sum += i; // } // return sum; // }; //使用Lambda表达式表示 GetSum getSum = (a, b) => { int sum = 0; for (int i = a; i <= b; i++) { sum += a; } return(sum); }; int res = getSum(1, 100); }
private static void DelegateExample() { GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); }
static void Main(string[] args) { // Anonymous Methods GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); }
static void Main(string[] args) { using (var qsim = new QuantumSimulator()) { System.Console.WriteLine("Sum of 4 and 5 is"); var result = GetSum.Run(qsim, 4, 5).Result; System.Console.WriteLine(result); } }
static void Main(string[] args) { if ("the stuff before FileSystem.OI" == "") { GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); // https://youtu.be/lisiwUZJXqQ?t=4859 // lambda expression, used to acts as an anonymous function or expression tree Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(3, 5)); List <int> numList = new List <int> { 5, 10, 15, 20, 25 }; List <int> oddNums = numList.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.WriteLine(num + ", "); } } string[] custs = new string[] { "Tom", "Paul", "Greg" }; using (StreamWriter sw = new StreamWriter("custs.txt")) { foreach (string cust in custs) { sw.WriteLine(cust); } } string custName = ""; using (StreamReader sr = new StreamReader("custs.txt")) { while ((custName = sr.ReadLine()) != null) { Console.WriteLine(custName); } } Console.ReadLine(); }
static void Main(string[] args) { //1st example MSG msg1, msg2, msg3, msg4; msg1 = new MSG(ShowMessage1); msg2 = new MSG(ShowMessage2); msg3 = new MSG(ShowMessage3); msg4 = msg1 + msg2 + msg3; // msg4(); //============================================================================ //2nd example. MSG ms = new MSG(ShowMessage1); //register to another function. ms += ShowMessage2; //register to another function ms += ShowMessage3; //unregister from exist function ms -= ShowMessage2; //ms(); //============================================================================ //3rd example. GetSum num = new GetSum(GetSumWithFive); num += GetSumWithTen; num -= GetSumWithTen; int sum = num(15); //Console.WriteLine("Total is : {0}", sum); //============================================================================ //4th example. GetOut go = new GetOut(GetOut5); go += GetOut10; int outValue = -1; go(out outValue); Console.WriteLine("The Output Value is : {0}", outValue); }
static void Main(string[] args) { // create a variable of the type of the enum we created, then we can assign it a value Temperature micTemp = Temperature.Low; // Here is a switch that will check and print the value of micTemp switch (micTemp) { case Temperature.Freeze: Console.WriteLine("Temp on Freezing"); break; case Temperature.Low: Console.WriteLine("Temp on Low"); break; case Temperature.Warm: Console.WriteLine("Temp on Warm"); break; case Temperature.Boil: Console.WriteLine("Temp on Boil"); break; } // Creating a Customer, which is a struct. Customers bob = new Customers(); // giving the object som value and then printing those values to the screen. bob.createCust("Bob", 15.50, 12345); bob.showCust(); // This is also called an anonymous method GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); // Lambda experssions are like anonymous methods. Often used with lists. Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("6 + 3 = " + getSum.Invoke(5, 3)); }
public void MyTestInitialize() { Console.WriteLine("TestInitialize" + this.TestContext.TestName); this._Target = new GetSum(); this._BookItems = new List <TestItem>() { new TestItem { ID = 1, Cost = 1, Revenue = 11, SellPrice = 21 }, new TestItem { ID = 2, Cost = 2, Revenue = 12, SellPrice = 22 }, new TestItem { ID = 3, Cost = 3, Revenue = 13, SellPrice = 23 }, new TestItem { ID = 4, Cost = 4, Revenue = 14, SellPrice = 24 }, new TestItem { ID = 5, Cost = 5, Revenue = 15, SellPrice = 25 }, new TestItem { ID = 6, Cost = 6, Revenue = 16, SellPrice = 26 }, new TestItem { ID = 7, Cost = 7, Revenue = 17, SellPrice = 27 }, new TestItem { ID = 8, Cost = 8, Revenue = 18, SellPrice = 28 }, new TestItem { ID = 9, Cost = 9, Revenue = 19, SellPrice = 29 }, new TestItem { ID = 10, Cost = 10, Revenue = 20, SellPrice = 30 }, new TestItem { ID = 11, Cost = 11, Revenue = 21, SellPrice = 31 } }; }
static void Main(string[] args) { // Delegates // Anonomous Methods // have no name and the return type is defined strictly by the // return type used within the method implicitly // MethodName name = delegate(dataType name, dataType name2...) GetSum sum = delegate(double number1, double number2) { return(number1 + number2); }; Console.WriteLine("5 plus 10 = " + sum(5, 10)); Console.WriteLine("\nPress any key to close..."); Console.ReadKey(); //END of Main }
// The ```Main``` method is a static method that resides inside a class or a struct. // The parameter of the Main method, args, is a string array that contains the // command-line arguments used to invoke the program. Unlike in C++, the array // does not include the name of the executable (exe) file. static void Main(string[] args) { // --------------- Basics ------------------ Program.PrintHeader("Basics"); // Simple Hello world Console.Write(":) "); //Doesn't end with a line break Console.WriteLine("Hello World!"); //Ends with a line break // Input-Output Console.Write("What is your favorite color? "); string color = Console.ReadLine(); Console.WriteLine("Hey! " + color + " is a cool color"); // Datatypes /* * bool * char - 16 bit unicode * int, long, decimal, float, double (listed in increasing order by max value, use datatype.MaxValue to get their size) */ // String concatenation for data type conversion, the '+' works. int myNumber = 42; Console.WriteLine("What is the answer to life the universe and everything? It's " + myNumber); // var keyword - when used, assumes data type. Data type is static though, so once a var has a data type it won't change var someVariable = "A Dance With Dragons"; Console.WriteLine("someVariable: " + someVariable + ", datatype: {0}", someVariable.GetTypeCode()); // Type casting double numberPi = 3.14159; int intPi = (int)numberPi; // ---------- CONDITIONALS ---------- Program.PrintHeader("Conditionals"); // Relational Operators : > < >= <= == != // Logical Operators : && || ^ ! // If Statement int age = 17; if ((age >= 5) && (age <= 7)) { Console.WriteLine("Go to elementary school"); } else if ((age > 7) && (age < 13)) { Console.WriteLine("Go to middle school"); } else { Console.WriteLine("Go to high school"); } if ((age < 14) || (age > 67)) { Console.WriteLine("You shouldn't work"); } Console.WriteLine("! true = " + (!true)); // Ternary Operator bool canDrive = age >= 16 ? true : false; // Switch is used when you have limited options // Fall through isn't allowed with C# unless there are no statements between cases // You can't check multiple values at once switch (age) { case 0: Console.WriteLine("Infant"); break; case 1: case 2: Console.WriteLine("Toddler"); // Goto can be used to jump to a label elsewhere in the code goto Cute; default: Console.WriteLine("Child"); break; } // Lable we can jump to with Goto Cute: Console.WriteLine("Toddlers are cute"); // ---------- LOOPING ---------- Program.PrintHeader("Looping"); int i = 0; while (i < 10) { // If i = 7 then skip the rest of the code and start with i = 8 if (i == 7) { i++; continue; } // Jump completely out of the loop if i = 9 if (i == 9) { break; } // You can't convert an int into a bool : Print out only odds if ((i % 2) > 0) { Console.WriteLine(i); } i++; } // The do while loop will go through the loop at least once string guess; do { Console.WriteLine("Guess a Number "); guess = Console.ReadLine(); } while (!guess.Equals("15")); // How to check String equality // Puts all changes to the iterator in one place for (int j = 0; j < 10; j++) { if ((j % 2) > 0) { Console.WriteLine(j); } } // foreach cycles through every item in an array or collection string randStr = "Here are some random characters"; foreach (char c in randStr) { Console.Write(c + " "); } // ---------- STRINGS ---------- Program.PrintHeader("Strings"); // Escape Sequences : \' \" \\ \b \n \t string sampString = "A bunch of random words"; // Check if empty Console.WriteLine("Is empty " + String.IsNullOrEmpty(sampString)); Console.WriteLine("Is empty " + String.IsNullOrWhiteSpace(sampString)); Console.WriteLine("String Length " + sampString.Length); // Find a string index (Starts with 0) Console.WriteLine("Index of bunch " + sampString.IndexOf("bunch")); // Get a substring Console.WriteLine("2nd Word " + sampString.Substring(2, 6)); string sampString2 = "More random words"; // Are strings equal Console.WriteLine("Strings equal " + sampString.Equals(sampString2)); // Compare strings Console.WriteLine("Starts with A bunch " + sampString.StartsWith("A bunch")); Console.WriteLine("Ends with words " + sampString.EndsWith("words")); // Trim white space at beginning and end or (TrimEnd / TrimStart) sampString = sampString.Trim(); // Replace words or characters sampString = sampString.Replace("words", "characters"); Console.WriteLine(sampString); // Remove starting at a defined index up to the second index sampString = sampString.Remove(0, 2); Console.WriteLine(sampString); // Join values in array and save to string string[] names = new string[3] { "Matt", "Joe", "Paul" }; Console.WriteLine("Name List " + String.Join(", ", names)); // Formatting : Currency, Decimal Places, Before Decimals, Thousands Separator string fmtStr = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 1.56, 15.567, .56, 1000); Console.WriteLine(fmtStr.ToString()); // ---------- STRINGBUILDER ---------- // Each time you create a string you actually create another string in memory // StringBuilders are used when you want to be able to edit a string without creating new ones Program.PrintHeader("StringBuilder"); StringBuilder sb = new StringBuilder(); // Append a string to the StringBuilder (AppendLine also adds a newline at the end) sb.Append("This is the first sentence."); // Append a formatted string sb.AppendFormat("My name is {0} and I live in {1}", "Derek", "Pennsylvania"); // Clear the StringBuilder // sb.Clear(); // Replaces every instance of the first with the second sb.Replace("a", "e"); // Remove characters starting at the index and then up to the defined index sb.Remove(5, 7); // Out put everything Console.WriteLine(sb.ToString()); // ---------- ARRAYS ---------- Program.PrintHeader("Arrays"); // Declare an array int[] randNumArray; // Declare the number of items an array can contain int[] randArray = new int[5]; // Declare and initialize an array int[] randArray2 = { 1, 2, 3, 4, 5 }; // Get array length Console.WriteLine("Array Length " + randArray2.Length); // Get item at index Console.WriteLine("Item 0 " + randArray2[0]); // Cycle through array for (int j = 0; j < randArray2.Length; j++) { Console.WriteLine("{0} : {1}", j, randArray2[j]); } // Cycle with foreach foreach (int num in randArray2) { Console.WriteLine(num); } // Get the index of an item or -1 Console.WriteLine("Where is 1 " + Array.IndexOf(randArray2, 1)); string[] names2 = { "Lauren", "Orsini", "Lol" }; // Join an array into a string string nameStr = string.Join(", ", names2); Console.WriteLine(nameStr); // Split a string into an array string[] nameArray = nameStr.Split(','); // Create a multidimensional array int[,] multArray = new int[5, 3]; // Create and initialize a multidimensional array int[,] multArray2 = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; // Cycle through multidimensional array foreach (int num in multArray2) { Console.WriteLine(num); } // Cycle and have access to indexes for (int x = 0; x < multArray2.GetLength(0); x += 1) { for (int y = 0; y < multArray2.GetLength(1); y += 1) { Console.WriteLine("{0} | {1} : {2}", x, y, multArray2[x, y]); } } // ---------- LISTS ---------- // A list unlike an array automatically resizes Program.PrintHeader("Lists"); // Create a list and add values List <int> numList = new List <int>(); numList.Add(5); numList.Add(15); numList.Add(25); // Add an array to a list int[] randArray3 = { 1, 2, 3, 4, 5 }; numList.AddRange(randArray3); // Clear a list // numList.Clear(); // Copy an array into a List List <int> numList2 = new List <int>(randArray3); // Create a List with array List <int> numList3 = new List <int>(new int[] { 1, 2, 3, 4 }); // Insert in a specific index numList.Insert(1, 10); // Remove a specific value numList.Remove(5); // Remove at an index numList.RemoveAt(2); // Cycle through a List with foreach or for (int j = 0; j < numList.Count; j++) { Console.WriteLine(numList[j]); } // Return the index for a value or -1 Console.WriteLine("4 is in index " + numList3.IndexOf(4)); // Does the List contain a value Console.WriteLine("5 in list " + numList3.Contains(5)); // Search for a value in a string List List <string> strList = new List <string>(new string[] { "Tom", "Paul" }); Console.WriteLine("Tom in list " + strList.Contains("tom", StringComparer.OrdinalIgnoreCase)); // Sort the List strList.Sort(); // ---------- EXCEPTION HANDLING ---------- // All the exceptions // msdn.microsoft.com/en-us/library/system.systemexception.aspx#inheritanceContinued Program.PrintHeader("Exception Handling"); try { Console.Write("Divide 10 by "); int num = int.Parse(Console.ReadLine()); Console.WriteLine("10 / {0} = {1}", num, (10 / num)); } // Specifically catches the divide by zero exception catch (DivideByZeroException ex) { Console.WriteLine("Can't divide by zero"); // Get additonal info on the exception Console.WriteLine(ex.GetType().Name); Console.WriteLine(ex.Message); // Throw the exception to the next inline // throw ex; // Throw a specific exception throw new InvalidOperationException("Operation Failed", ex); } // Catches any other exception catch (Exception ex) { Console.WriteLine("An error occurred"); Console.WriteLine(ex.GetType().Name); Console.WriteLine(ex.Message); } // ---------- CLASSES & OBJECTS ---------- Program.PrintHeader("Classes and Objects"); Animal bulldog = new Animal(13, 50, "Spot", "Woof"); Console.WriteLine("{0} says {1}", bulldog.name, bulldog.sound); bulldog.RunAnimal(); Console.WriteLine("No. of Animals " + Animal.getNumOfAnimals()); // ---------- ENUMS ---------- Program.PrintHeader("Enums"); Temperature micTemp = Temperature.Low; Console.Write("What Temp : "); Console.ReadLine(); switch (micTemp) { case Temperature.Freeze: Console.WriteLine("Temp on Freezing"); break; case Temperature.Low: Console.WriteLine("Temp on Low"); break; case Temperature.Warm: Console.WriteLine("Temp on Warm"); break; case Temperature.Boil: Console.WriteLine("Temp on Boil"); break; } // ---------- STRUCTS ---------- Program.PrintHeader("Structs"); Customers bob = new Customers(); bob.createCust("Bob", 15.50, 12345); bob.showCust(); // ---------- ANONYMOUS METHODS ---------- // An anonymous method has no name and its return type is defined by the return used in the method Program.PrintHeader("Anonymous Methods"); GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); // ---------- LAMBDA EXPRESSIONS ---------- // A lambda expression is used to act as an anonymous function or expression tree Program.PrintHeader("Lambda Expressions"); // You can assign the lambda expression to a function instance Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); // Get odd numbers from a list List <int> numList4 = new List <int> { 5, 10, 15, 20, 25 }; // With an Expression Lambda the input goes in the left (n) and the statements go on the right List <int> oddNums = numList4.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.Write(num + ", "); } // ---------- FILE I/O ---------- // The StreamReader and StreamWriter allows you to create text files while reading and // writing to them Program.PrintHeader("File I/0"); string[] custs = new string[] { "Tom", "Paul", "Greg" }; using (StreamWriter sw = new StreamWriter("custs.txt")) { foreach (string cust in custs) { sw.WriteLine(cust); } } string custName = ""; using (StreamReader sr = new StreamReader("custs.txt")) { while ((custName = sr.ReadLine()) != null) { Console.WriteLine(custName); } } //------------------Animal Class------------------------- Program.PrintHeader("More Classes"); // Create an Animal object and call the constructor Animal spot = new Animal(15, 10, "Spot", "Woof"); // Get object values with the dot operator Console.WriteLine("{0} says {1}", spot.name, spot.sound); // Calling a static method Console.WriteLine("Number of Animals " + Animal.getNumOfAnimals()); // Calling an object method Console.WriteLine(spot.toString()); Console.WriteLine("3 + 4 = " + spot.getSum(3, 4)); // You can assign attributes by name Console.WriteLine("3.4 + 4.5 = " + spot.getSum(num2: 3.4, num1: 4.5)); // You can create objects with an object initializer Animal grover = new Animal { name = "Grover", height = 16, weight = 18, sound = "Grrr" }; Console.WriteLine(grover.toString()); // Create a subclass Dog object Dog spike = new Dog(); Console.WriteLine(spike.toString()); spike = new Dog(20, 15, "Spike", "Grrr Woof", "Chicken"); Console.WriteLine(spike.toString()); // One way to implement polymorphism is through an abstract class Shape rect = new Rectangle(5, 5); Shape tri = new Triangle(5, 5); Console.WriteLine("Rect Area " + rect.area()); Console.WriteLine("Trit Area " + tri.area()); // Using the overloaded + on 2 Rectangles Rectangle combRect = new Rectangle(5, 5) + new Rectangle(5, 5); Console.WriteLine("combRect Area = " + combRect.area()); // ---------- GENERICS ---------- // With Generics you don't have to specify the data type of an element in a class or method KeyValue <string, string> superman = new KeyValue <string, string>("", ""); superman.key = "Superman"; superman.value = "Clark Kent"; superman.showData(); // Now use completely different types KeyValue <int, string> samsungTV = new KeyValue <int, string>(0, ""); samsungTV.key = 123456; samsungTV.value = "a 50in Samsung TV"; samsungTV.showData(); Console.Write("Hit Enter to Exit"); }
static void Main(string[] args) { KeyValue <string, string> superman = new KeyValue <string, string>("", ""); superman.key = "Superman"; superman.value = "Clark Kent"; KeyValue <int, string> samsungTV = new KeyValue <int, string>(0, ""); samsungTV.key = 12345; samsungTV.value = "a 50 in Samsung TV"; superman.showData(); samsungTV.showData(); //Enum playing Temperature micTemp = Temperature.Warm; switch (micTemp) { case Temperature.Freeze: Console.WriteLine("Temp on freezing"); break; case Temperature.Low: Console.WriteLine("Temp on Low"); break; case Temperature.Warm: Console.WriteLine("Temp on Warm"); break; case Temperature.Boil: Console.WriteLine("Temp on Boil"); break; default: Console.WriteLine("Temp on 0"); break; } //Struct playing Costumers bob = new Costumers(); bob.createCust("Bob", 15.50, 12345); bob.showCust(); //Anonymous delegate showing GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 =" + sum(5, 10)); //Lambda function Lambda Expressions Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine(" 5+3 = " + getSum.Invoke(5, 3)); List <int> numList = new List <int> { 5, 10, 15, 20, 25 }; List <int> oddNums = numList.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.WriteLine(num); } }
static void Main(string[] args) { //Create a new Animal object Animal spot = new Animal(15, 10, "Spot", "Woof"); //Print info about the Animal object Console.WriteLine("{0} says {1}", spot.name, spot.sound); //Get the number of Animal objects. You need the class name for static methods //as they belong to the class itself, not the objects Console.WriteLine("Number of Animals = " + Animal.getNumOfAnimals()); //Print the Animal object's information Console.WriteLine(spot.toString()); //METHOD OVERLOADING: //------------------------- Console.WriteLine(spot.getSum(1, 2)); //The integer version Console.WriteLine(spot.getSum(1.4, 2.7)); //The double version Console.WriteLine(spot.getSum(num2: 2.7, num1: 1.4)); //The different-order version //Create a new Animal object using the Object Initialiser: Animal grover = new Animal { name = "Grover", height = 16, weight = 18, sound = "Grrrr" }; //The total number of Animals has increased Console.WriteLine("Number of Animals = " + Animal.getNumOfAnimals()); Dog spike = new Dog(); Console.WriteLine(spike.toString());//Display the default initialised Dog Object spike //Overwrite spike's information spike = new Dog(20, 15, "Spike", "Grr", "Chicken"); Console.WriteLine(spike.toString());//Display the overwritten Dog Object spike //POLYMORPHISM USING ABSTRACT CLASSES: //---------------------------------------------------------------------------------------------------------- //Both Shapes but one is a Rectangle and the other a Triangle //Since both are Shapes, they can go into Shape arrays despite technically being different classes Shape rect = new Rectangle(5, 5); Shape tri = new Triangle(5, 5); //Polymorphism makes it so that the correct area() method is called for each Console.WriteLine("Area of rect = " + (rect.area())); Console.WriteLine("Area of tri = " + (tri.area())); //The following will work thanks to the Operator Overloading done in the Rectangle class Rectangle combRect = new Rectangle(5, 5) + new Rectangle(5, 5); //Display combRect's area Console.WriteLine("Area of combRect = " + (combRect.area())); //GENERICS CONTINUED: //----------------------------------------------------- KeyValue <string, string> superman = new KeyValue <string, string>("", ""); superman.key = "Superman"; superman.value = "Clark Kent"; KeyValue <int, string> samsungTV = new KeyValue <int, string>(0, ""); samsungTV.key = 12345; samsungTV.value = "a 50-inch Samsung TV"; superman.showData(); samsungTV.showData(); //ENUMERATED TYPES(ENUMs) CONTINUED: //--------------------------------------------------- Temperature micTemp = Temperature.Warm; switch (micTemp) { case Temperature.Freeze: Console.WriteLine("Temp on Freezing"); break; case Temperature.Low: Console.WriteLine("Temp on Low"); break; case Temperature.Warm: Console.WriteLine("Temp on Warm"); break; case Temperature.Boil: Console.WriteLine("Temperature on Boil"); break; } //STRUCTS CONTINUED: //------------------------------------------------------------------------ Customers bob = new Customers(); bob.createCust("Bob", 15.50, 12345); bob.showCust(); //DELEGATES CONTINUED: //------------------------------------------------------------------------ //An anonymus method has no name and it's return type is defined by the return used in the method GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); //Lamda expressions: Used to act as an anonymus function or an expression trait //Can assign the Lamda expression to a function instance Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); //They're often used with lists: List <int> numList = new List <int> { 5, 10, 15, 20, 25 }; List <int> oddNums = numList.Where(n => n % 2 == 1).ToList();//Place all odd numbers in the oddNums List foreach (int num in oddNums) { Console.WriteLine(num + ", "); } //FILE I/O: //----------------------------------------------------------------------------------------------- string[] custs = new string[] { "Tom", "Paul", "Greg" }; //Create custs.txt if it doesn't exist and write to it: //HAD TO MAKE CustomerStorage FOLDER MYSELF!!!!!!! using (StreamWriter sw = new StreamWriter("CustomerStorage/custs.txt")) { foreach (string cust in custs) { Console.WriteLine("Adding {0} to the file", cust); sw.WriteLine(cust); } } //Read the contents of custs.txt until you reach the end: string custName = ""; //HAD TO MAKE CustomerStorage FOLDER MYSELF!!!!!!! using (StreamReader sr = new StreamReader("CustomerStorage/custs.txt")) { while ((custName = sr.ReadLine()) != null) { Console.WriteLine(custName);//Display the contents of custs.txt } } //Used to keep the window open. C#'s version of C's getchar() Console.ReadKey(); }
static void Main(string[] args) { /* Use RandomValue class */ //RandomValue rand = new RandomValue(); //rand.GetRandomValue(); //AddDivider(); /* Use DiffTypes class */ //DiffTypes diffTypes = new DiffTypes(); //diffTypes.DisplayTypes(); //AddDivider(); /* Use MathActions class */ //MathActions mathAct = new MathActions(); //mathAct.ShowMeThePowerOfMath(); //AddDivider(); /* Loops */ //Loops loopExmpl = new Loops(); //loopExmpl.LoopExamples(); //AddDivider(); /* Strings */ //StrongString str = new StrongString(); //str.StringExamples(); //AddDivider(); /* StringBuilder */ //StrBuilder sb = new StrBuilder(); //sb.Sbuilder(); //AddDivider(); /* Arrays */ //ArraySample arr = new ArraySample(); //arr.Arr(); //AddDivider(); /* Lists */ //ListExample lst = new ListExample(); //lst.GetListExample(); //AddDivider(); /* Exceptions */ //ExeptionExample exptSample = new ExeptionExample(); //exptSample.GetExeptionExample(); //AddDivider(); /* Work with classes and class constructor */ //Animal myPet = new Animal(); //myPet.AnimalFarm(); //AddDivider(); /* Abstractions */ //Abstractions abst = new Abstractions(); //abst.ShowMeAbstractions(); /* Generic classes */ //GenericExample gnrc = new GenericExample(); //gnrc.ShowGenericExample(); /* Enum */ //EnumExample enumSample = new EnumExample(); //enumSample.ShowEnumExample(); /* Struct */ //StructExample structSmpl = new StructExample(); //structSmpl.ShowStructExample(); /* Delegate */ GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); /* Lamdba expressions */ // 1) Anonymous functions Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); // 2) Work with lists List <int> numList = new List <int> { 5, 10, 15, 20, 25 }; List <int> oddNums = numList.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.WriteLine(num); } }
// Code in the main function is executed static void Main(string[] args) { // Prints string out to the console with a line break (Write = No Line Break) Console.WriteLine("What is your name : "); // Accept input from the user string name = Console.ReadLine(); // You can combine Strings with + Console.WriteLine("Hello " + name); // ---------- DATA TYPES ---------- MoreConcepts.DataTypes(); // ---------- MATH ---------- MoreConcepts.MathMethods(); // ---------- CONDITIONALS ---------- MoreConcepts.Conditionals(); // ---------- Looping ---------- MoreConcepts.loops(); // ---------- STRINGS ---------- MoreConcepts.StringConcept(); // ----------STRINGBUILDER---------- MoreConcepts.StringBuilder(); // ---------- ARRAYS ---------- MoreConcepts.Arrays(); // ---------- LISTS ---------- MoreConcepts.List(); // ---------- EXCEPTION HANDLING ---------- MoreConcepts.Exception(); // ---------- CLASSES & OBJECTS ---------- Animal bulldog = new Animal(13, 50, "Spot", "Woof"); Console.WriteLine("{0} says {1}", bulldog.Name, bulldog.sound); // Console.WriteLine("No. of Animals " + Animal.getNumOfAnimals()); // ---------- ENUMS ---------- Temperature micTemp = Temperature.Low; Console.Write("What Temp : "); Console.ReadLine(); switch (micTemp) { case Temperature.Freeze: Console.WriteLine("Temp on Freezing"); break; case Temperature.Low: Console.WriteLine("Temp on Low"); break; case Temperature.Warm: Console.WriteLine("Temp on Warm"); break; case Temperature.Boil: Console.WriteLine("Temp on Boil"); break; } // ---------- STRUCTS ---------- Customers bob = new Customers(); bob.createCust("Bob", 15.50, 12345); bob.showCust(); // ---------- ANONYMOUS METHODS ---------- // An anonymous method has no name and its return type is defined by the return used in the method GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); // ---------- LAMBDA EXPRESSIONS ---------- // A lambda expression is used to act as an anonymous function or expression tree // You can assign the lambda expression to a function instance Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); // Get odd numbers from a list List <int> numList = new List <int> { 5, 10, 15, 20, 25 }; // With an Expression Lambda the input goes in the left (n) and the statements go on the right List <int> oddNums = numList.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.Write(num + ", "); } // ---------- FILE I/O ---------- // The StreamReader and StreamWriter allows you to create text files while reading and // writing to them string[] custs = new string[] { "Tom", "Paul", "Greg" }; using (StreamWriter sw = new StreamWriter("custs.txt")) { foreach (string cust in custs) { sw.WriteLine(cust); } } string custName = ""; using (StreamReader sr = new StreamReader("custs.txt")) { while ((custName = sr.ReadLine()) != null) { Console.WriteLine(custName); } } Console.Write("Hit Enter to Exit"); string exitApp = Console.ReadLine(); }
static void Main(string[] args) { /* * Console.WriteLine("What is your name "); * string name = Console.ReadLine(); * Console.WriteLine("Hello "+name); * Console.ReadLine(); * * int maxInt = int.MaxValue; * long maxLong = long.MaxValue; * decimal maxDec = decimal.MaxValue; * float maxFloat = float.MaxValue; * double maxDouble = double.MaxValue; * * Console.WriteLine(maxInt); * Console.WriteLine(maxLong); * Console.WriteLine(maxDec); * Console.WriteLine(maxFloat); * Console.WriteLine(maxDouble); * * var anotherName = "Tom"; * Console.WriteLine("Another name is a {0}", anotherName); * * double number1 = 10.5; * double number2 = 15; * * Console.WriteLine("Math.Abs(number1) "+ (Math.Abs(number1))); * Console.WriteLine("Math.Ceiling(number1) "+ (Math.Ceiling(number1))); * Console.WriteLine("Math.Floor(number1) "+ (Math.Floor(number1))); * Console.WriteLine("Math.Max(number1, number2) "+ (Math.Max(number1, number2))); * Console.WriteLine("Math.Min(number1, number2) "+ (Math.Min(number1, number2))); * Console.WriteLine("Math.Pow(number1)//podnoszenie do potegi "+ (Math.Pow(number1,2))); * Console.WriteLine("Math.Round(number1) "+ (Math.Round(number1))); * Console.WriteLine("Math.Sqrt(number1) "+ (Math.Sqrt(number1))); * * * //Random Numbers * * Random rand = new Random(); * * * //Relational Operators: > < >= <= == != * //Logical Operators: && || ^ ! * * int age = rand.Next(1, 19); * Console.WriteLine("Random Number between 1 and 18: " + age); * * if ((age >= 5) && (age <= 7)) * { * Console.WriteLine("Go to elemantary school"); * } * else if ((age > 7) && (age < 13)) * { * Console.WriteLine("Go to middle school"); * } * else * { * Console.WriteLine("Go home"); * } * * bool canDrive = age >= 16 ? true : false; * * switch (age) * { * case 0: * Console.WriteLine("Infant"); * break; * case 1: * Console.WriteLine("Toddler"); * break; * default: * Console.WriteLine("Child"); * break; * } * * string guess; * do * { * Console.WriteLine("Guess a Number"); * guess = Console.ReadLine(); * } while (!guess.Equals("15")); * * * for (int i = 0; i < 10; i++) * { * if ((i % 2) > 0) * { * Console.WriteLine(i); * } * } * * string randStr = " Uh oh ah random krach"; * foreach (char a in randStr) * { * Console.WriteLine(a); * } * * /* \' \" \\ \b \n \t */ /* * Console.WriteLine("Empty? " + String.IsNullOrEmpty(randStr)); * Console.WriteLine("Empty or just white spaces? " + String.IsNullOrWhiteSpace(randStr)); * Console.WriteLine("Length: " + randStr.Length); * * Console.WriteLine("Index of \"oh\" {0}", randStr.IndexOf("oh")); * Console.WriteLine("2nd word: {0}", randStr.Substring(3, 4)); * * bool b = randStr.StartsWith("a"); * bool b2 = randStr.EndsWith("h"); * * Console.WriteLine("Trim:{0}", randStr.Trim()); //TrimEnd(), TrimStart() * Console.WriteLine("Replace: {0}", randStr.Replace("random", "super")); * Console.WriteLine("Remove: {0}", randStr.Remove(0, 3)); */ string[] names = new string[3] { "Matt", "Joe", "Paul" }; int[] MyArray = { 1, 2, 3, 4 }; for (int i = 0; i < MyArray.Length; i++) { Console.WriteLine("{0}: {1}", i, MyArray[i]); } foreach (int a in MyArray) { Console.WriteLine(a); } //Multidimential arrays int[,] multArray = new int[5, 3]; int[,] multArray2 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; for (int i = 0; i < multArray2.GetLength(0); i++) { for (int j = 0; j < multArray2.GetLength(1); j++) { Console.WriteLine("{0} | {1} : {2}", i, j, multArray2[i, j]); } } //List - resize for you List <int> numList = new List <int>(); numList.Add(5); numList.Add(25); numList.Add(35); int[] randArray = { 1, 2, 3, 4, 5 }; numList.AddRange(randArray); List <int> numList2 = new List <int>(randArray); List <int> numList3 = new List <int>(new int[] { 1, 2, 3, 4, 4, 5, 6, 7 }); numList.Insert(5, 10); //numList.Remove(5); for (int i = 0; i < numList.Count; i++) { Console.WriteLine(numList[i]); } Console.WriteLine("4 is in index: " + numList.IndexOf(4)); Console.WriteLine("5 in List: " + numList.Contains(5)); List <string> strList = new List <string>(new String[] { "Tom", "Jerry" }); Console.WriteLine("Tom in list " + strList.Contains("tom", StringComparer.OrdinalIgnoreCase)); strList.Sort(); //alfabetycznie for (int i = 0; i < strList.Count; i++) { Console.WriteLine(strList[i]); } //Exceptions try { Console.Write("Divide 10 by "); int num = int.Parse(Console.ReadLine()); Console.WriteLine("10 / {0} = {1}", num, (10 / num)); } catch (DivideByZeroException ex) { Console.WriteLine("Can't divide by zero!"); Console.WriteLine(ex.GetType().Name); Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine(ex.GetType().Name); Console.WriteLine(ex.Message); } //Classes Animal spot = new Animal(15, 10, "Spot", "Woof"); Console.WriteLine("{0} says {1}.", spot.name, spot.sound); Console.WriteLine("Number of animals: " + Animal.getNumOfAnimals()); Console.WriteLine(spot.toString()); Animal Burczek = new Animal() { name = "Burczek", height = 12, weight = 6, sound = "Grrrr" }; Dog burek = new Dog(); Console.WriteLine(burek.toString()); burek = new Dog(20, 15, "Burek", "Woof", "Chicken"); Console.WriteLine(burek.toString()); Console.WriteLine(spot.getSum(num1: 1.4, num2: 2.7)); Console.WriteLine("Number of animals: " + Animal.getNumOfAnimals()); //Shapes//////////////// Shape rect = new Rectangle(5, 5); Shape tri = new Triangle(5, 5); Console.WriteLine("Rectangle area: " + rect.area()); Console.WriteLine("Triangle area: " + tri.area()); Rectangle combRect = new Rectangle(5, 5) + new Rectangle(5, 5); Console.WriteLine("combRect area: " + combRect.area()); //Generics KeyValue <string, string> superman = new KeyValue <string, string>("", ""); superman.key = "Superman"; superman.value = "Clark Kent"; KeyValue <int, string> samsungTV = new KeyValue <int, string>(0, ""); samsungTV.key = 1234; samsungTV.value = "A 50\" Samsung TV"; superman.showData(); samsungTV.showData(); //Enums Temperature microwaveTemp = Temperature.Low; switch (microwaveTemp) { case Temperature.Freeze: Console.WriteLine("Temp on Freezing"); break; case Temperature.Low: Console.WriteLine("Temp on Low"); break; case Temperature.Warm: Console.WriteLine("Temp on Warm"); break; case Temperature.Boil: Console.WriteLine("Temp on Boil"); break; } //Structs Customers bob = new Customers(); bob.createCust("BoB", 15.60, 12345); bob.showCust(); //Anonymous Methods GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5+ 10 = " + sum(5, 10)); //Lambda Expressions Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); List <int> CoolNumList = new List <int>() { 5, 10, 15, 20, 25 }; List <int> OddNums = CoolNumList.Where(n => n % 2 == 1).ToList(); foreach (var q in OddNums) { Console.WriteLine(q); } Console.ReadLine(); }
static void Main(string[] args) { // init object using constructor Animal spot = new Animal(15, 10, "Spot", "Woof"); Animal jackie = new Animal { name = "Jackie", height = 7, weight = 13, sound = "ruff" }; //calling object attributes Console.WriteLine("{0} says {1}", spot.name, spot.sound); //calling class methods Console.WriteLine("Number of Animals " + Animal.getNumOfAnimals()); //calling object methods Console.WriteLine(spot.toString()); //method overloading allows multiple types Console.WriteLine(spot.getSum(1, 2)); Console.WriteLine(spot.getSum(1.2, 3.5)); Console.WriteLine(spot.getSum(num2: 3.7, num1: 2.5)); Dog spike = new Dog(); Console.WriteLine(spike.toString()); spike = new Dog(20, 15, "Spike", "Grr", "Chicken"); Console.WriteLine(spike.toString()); Shape rect = new Rectangle(5, 5); Shape tri = new Triangle(5, 5); Console.WriteLine("Rect area = " + rect.area()); Console.WriteLine("Tri area = " + tri.area()); Rectangle combRect = new Rectangle(5, 5) + new Rectangle(5, 5); Console.WriteLine("combRect Area = " + combRect.area()); KeyValue <string, string> superman = new KeyValue <string, string>("", ""); superman.key = "Superman"; superman.value = "Clark Kent"; superman.showData(); KeyValue <int, string> samsungTv = new KeyValue <int, string>(0, ""); samsungTv.key = 1234; samsungTv.value = "50 inch tv"; samsungTv.showData(); Temperature micTemp = Temperature.Low; Customers bob = new Customers(); bob.createCust("Bob", 15.50, 12345); bob.showCust(); GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); List <int> numList4 = new List <int> { 5, 10, 15, 20, 25 }; List <int> oddNums = numList4.Where(nameof => nameof % 2 == 1).ToList(); foreach (int num in oddNums) { Console.WriteLine(num + ", "); } //comments /* multiline * comments */ /* commenting old code to clean up terminal * * * Console.Write("What is your name? "); * string name = "Pierce"; * // string name = Console.ReadLine(); * Console.WriteLine("Hello " + name); * * // booleans * bool canVote = true; * * // single 16-bit character * char grade = 'A'; * * // Integer with a max number of 2,147,483,647 * int maxInt = int.MaxValue; * Console.WriteLine(maxInt); * * // Long Integer with a max value of 9,223,372,036,854,775,807 * long maxLong = long.MaxValue; * Console.WriteLine(maxLong); * * // Float is a 32 bit number with MaxValue of 3.402823E+38 !!ONLY HAS 7 decimals of precision! * float maxFloat = float.MaxValue; * Console.WriteLine(maxFloat); * * // Double is a 32 bit number with a MaxValue of 1.79769313486232E+308 !!Precise to 15 decimals * double maxDouble = double.MaxValue; * Console.WriteLine(maxDouble); * * // Method to get data type of a variable * Console.WriteLine("maxDouble is a {0}", maxDouble.GetTypeCode()); * * //standard math operators * Console.WriteLine("5 + 3 = " + (5 + 3)); * Console.WriteLine("5 - 3 = " + (5 - 3)); * Console.WriteLine("5 * 3 = " + (5 * 3)); * Console.WriteLine("5 / 3 = " + (5 / 3)); * Console.WriteLine("5 % 3 = " + (5 % 3)); * * int i = 0; * * //standard incrementers * // prints to console THEN increments * Console.WriteLine("i++ =" + (i++)); * * // increments THEN prints to console * Console.WriteLine("++i =" + (++i)); * * // prints to console THEN decrements * Console.WriteLine("i-- =" + (i--)); * * // decrements THEN prints to console * Console.WriteLine("--i =" + (--i)); * * //standard math + variable reassignment * Console.WriteLine("i += 2 " + (i += 2)); * Console.WriteLine("i -= 2 " + (i -= 2)); * Console.WriteLine("i *= 2 " + (i *= 2)); * Console.WriteLine("i /= 2 " + (i /= 2)); * Console.WriteLine("i %= 2 " + (i %= 2)); * * * // data type reassignment * double pi = 3.14; * int intPi = (int)pi; * Console.WriteLine("pi is a " + pi.GetTypeCode()); * Console.WriteLine("intPi is an " + intPi.GetTypeCode()); * * * // more math functions * double num1 = 12.5; * double num2 = 19; * * // returns absolute value * Console.WriteLine("Math.Abs(num1) " + (Math.Abs(num1))); * * // returns number rounded up * Console.WriteLine("Math.Ceiling(num1) " + (Math.Ceiling(num1))); * * // returns number rounded down * Console.WriteLine("Math.Floor(num1) " + (Math.Floor(num1))); * * // takes in two integers, returns higher value * Console.WriteLine("Math.Max(num1, num2) " + (Math.Max(num1, num2))); * * // takes in two integers, returns lower value * Console.WriteLine("Math.Min(num1, num2) " + (Math.Min(num1, num2))); * * // returns first int to the power of second int * Console.WriteLine("Math.Pow(num1, num2) " + (Math.Pow(num1, num2))); * * // returns number rounded based on standard rules * Console.WriteLine("Math.Round(num1) " + (Math.Round(num1))); * * // returns square root of int * Console.WriteLine("Math.Sqrt(num1) " + (Math.Sqrt(num1))); * * * * // random numbers * Random rand = new Random(); * Console.WriteLine("Random Number between 1 and 10: " + (rand.Next(1, 11))); * * * * // Relational Operators: > < >= <= == != * // Logical Operators: && || ^ ! * // if/else and switch statements * int age = 17; * * if ((age >= 5) && (age <= 7)) * { * Console.WriteLine("Go to elementary school"); * } else if ((age > 7) && (age < 13)) * { * Console.WriteLine("Go to middle school"); * } else * { * Console.WriteLine("Go to high school"); * } * * if ((age < 14) || (age > 67)) * { * Console.WriteLine("You shouldn't work"); * } * * Console.WriteLine("!true = " + (!true)); * * bool canDrive = age >= 16 ? true : false; * * switch (age) * { * case 0: * Console.WriteLine("Infant"); * break; * case 1: * Console.WriteLine("Toddlers are terrible"); * break; * default: * Console.WriteLine("Child"); * break; * } * * * * * * // Loops * int j = 0; * * while(j < 10) * { * if (j == 7) * { * j++; * continue; // ignores rest of code and starts loop again. * } * * if (j == 9) * { * break; // breaks out of loop * } * * if (j % 2 > 0) * { * Console.WriteLine(j); * } * j++; * } * * * string guess; * * // do * // { * // Console.WriteLine("Guess a Number "); * // guess = Console.ReadLine(); * // } while (!guess.Equals("15")); * * for (int k = 0; k < 10; k++) * { * if (k % 2 > 0) * { * Console.WriteLine(k); * } * } * * string randStr = "Here are some random characters"; * * foreach(char c in randStr) * { * Console.WriteLine(c); * } * * * * // More string stuff * * escapes: \' // single quote \" // double quote \\ // backslash \\\b // backspace \\\n // newline \\\t // tab \\ \\ \\string sampString = "A bunch of random words"; \\string sampString2 = "more random words"; \\ \\Console.WriteLine("Is empty " + String.IsNullOrEmpty(sampString)); \\Console.WriteLine("Is white space " + String.IsNullOrWhiteSpace(sampString)); \\Console.WriteLine("Length of string is " + sampString.Length); \\ \\Console.WriteLine("Index of bunch " + sampString.IndexOf("bunch")); \\Console.WriteLine("2nd Word " + sampString.Substring(2, 6)); \\Console.WriteLine("Strings Equal? " + sampString.Equals(sampString2)); \\Console.WriteLine("Starts with \"A bunch\" " + sampString.StartsWith("A bunch")); \\Console.WriteLine("ends with random words " + sampString.EndsWith("random words")); \\ \\sampString = sampString.Trim(); // also TrimEnd and TrimStart \\ \\sampString.Replace("words", "characters"); \\Console.WriteLine(sampString); \\ \\sampString.Remove(0, 2); \\ \\string[] names = new string[3] {"Pierce", "Dad", "Melissa"}; \\ \\Console.WriteLine("Name List: " + String.Join(", ", names)); \\ \\// string fmtStr = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 1.56); \\ \\// Console.WriteLine(fmtStr); \\ \\ \\ \\ \\// String builder \\ \\StringBuilder sb = new StringBuilder(); \\ \\sb.Append("This is the first sentence. "); \\Console.WriteLine(sb); \\ \\sb.AppendFormat("My name is {0} and I live in {1}", "Pierce", "San Diego"); \\Console.WriteLine(sb); \\ \\//replaces all "a"s with "e"s \\sb.Replace("a","e"); \\Console.WriteLine(sb); \\ \\//deletes everything in index 5 UP TO BUT NOT INCLUDING 7 \\sb.Remove(5, 7); \\ \\sb.Clear(); \\ \\ \\ \\ \\//Arrays \\ \\int[] randNumArray; \\ \\int[] randArray = new int[5]; \\ \\int[] randArray2 = {1, 2, 3, 4, 5}; \\ \\Console.WriteLine("Array Length " + randArray2.Length); \\ \\Console.WriteLine("Array Item 0 " + randArray2[0]); \\ \\for (int k = 0; k< randArray2.Length; k++) \\{ \\ Console.WriteLine("{0} : {1}", k, randArray2[k]); \\} \\ \\foreach(int num in randArray2) \\{ \\ Console.WriteLine(num); \\} \\ \\Console.WriteLine("Where is 1? Index: " + Array.IndexOf(randArray2, 1)); \\ \\string[] familyNames = {"Pierce", "Melly", "Bruce"}; \\ \\string nameStr = string.Join(", ", familyNames); \\Console.WriteLine(nameStr); \\ \\string[] nameArray = nameStr.Split(','); \\Console.WriteLine(nameArray); \\ \\int[,] multArray = new int[5, 3]; \\ \\int[,] multArray2 = {{0, 1}, {2, 3}, {4, 5}}; \\ \\foreach(int num in multArray2) \\{ \\ Console.WriteLine(num); \\} \\ \\// for (int a = 0; a < multArray2.GetLength(0); a++) \\// { \\// for(int b = 0; b < multArray2.GetLength(1); b++) \\// { \\// Console.WriteLine("{0} | {1} : {2}" + a, b, multArray2[a,b]); \\// } \\// } \\ \\ \\ \\// Lists \\ \\List<int> numList = new List<int>(); \\ \\numList.Add(5); \\numList.Add(8); \\numList.Add(12); \\ \\int[] randArray3 = {1, 2, 3, 4, 5}; \\numList.AddRange(randArray); \\ \\List<int> numList2 = new List<int>(randArray3); \\ \\List<int> numList3 = new List<int>(new int[] {1, 2, 3, 4}); \\ \\// inserts "10" into index 1 of the list \\numList.Insert(1, 10); \\ \\// removes value 5 from the list \\numList.Remove(5); \\ \\// remove item at index of 2 from list \\numList.RemoveAt(2); \\ \\for (int c = 0; c < numList.Count; c++) \\{ \\ Console.WriteLine(numList[c]); \\} \\ \\// finds index of a value, returns -1 if not found \\Console.WriteLine("4 is in index " + numList3.IndexOf(4)); \\ \\Console.WriteLine("5 in List? " + numList.Contains(5)); \\ \\List<string> strList = new List<string>(new string[] {"Tom", "Paul"}); \\ \\Console.WriteLine("Tom in List? " + strList.Contains("Tom")); \\ \\strList.Sort(); \\ \\ \\ \\ \\//Exception handling \\ \\try \\{ \\ Console.Write("Divide 10 by "); \\ int num = int.Parse(Console.ReadLine()); \\ Console.WriteLine("10 / {0} = {1}", num, (10/num)); \\} \\ \\// catches specific exceptions \\catch(DivideByZeroException ex) \\{ \\ Console.WriteLine("Can't divide by zero"); \\ Console.WriteLine(ex.GetType().Name); \\ Console.WriteLine(ex.Message); \\ throw new InvalidOperationException("Operation Failed", ex); \\} \\ \\// generic exception handler \\catch(Exception ex) \\{ \\ Console.WriteLine(ex.GetType().Name); \\ Console.WriteLine(ex.Message); \\} \\ */ }
// Code in the main function is executed static void Main(string[] args) { // Prints string out to the console with a line break (Write = No Line Break) Console.WriteLine("What is your name : "); // Accept input from the user string name = Console.ReadLine(); // You can combine Strings with + Console.WriteLine("Hello " + name); // ---------- DATA TYPES ---------- // Booleans are true or false bool canVote = true; // Characters are single 16 bit unicode characters char grade = 'A'; // Integer with a max number of 2,147,483,647 int maxInt = int.MaxValue; // Long with a max number of 9,223,372,036,854,775,807 long maxLong = long.MaxValue; // Decimal has a maximum value of 79,228,162,514,264,337,593,543,950,335 // If you need something bigger look up BigInteger decimal maxDec = decimal.MaxValue; // A float is a 32 bit number with a maxValue of 3.402823E+38 with 7 decimals of precision float maxFloat = float.MaxValue; // A float is a 32 bit number with a maxValue of 1.797693134E+308 with 15 decimals of precision double maxDouble = double.MaxValue; // You can combine strings with other values with + Console.WriteLine("Max Int : " + maxDouble); // The dynamic data type is defined at run time dynamic otherName = "Paul"; otherName = 1; // The var data type is defined when compiled and then can't change var anotherName = "Tom"; // ERROR : anotherName = 2; Console.WriteLine("Hello " + anotherName); // How to get the type and how to format strings Console.WriteLine("anotherName is a {0}", anotherName.GetTypeCode()); // ---------- MATH ---------- Console.WriteLine("5 + 3 = " + (5 + 3)); Console.WriteLine("5 - 3 = " + (5 - 3)); Console.WriteLine("5 * 3 = " + (5 * 3)); Console.WriteLine("5 / 3 = " + (5 / 3)); Console.WriteLine("5.2 % 3 = " + (5.2 % 3)); int i = 0; Console.WriteLine("i++ = " + (i++)); Console.WriteLine("++i = " + (++i)); Console.WriteLine("i-- = " + (i--)); Console.WriteLine("--i = " + (--i)); Console.WriteLine("i += 3 " + (i += 3)); Console.WriteLine("i -= 2 " + (i -= 2)); Console.WriteLine("i *= 2 " + (i *= 2)); Console.WriteLine("i /= 2 " + (i /= 2)); Console.WriteLine("i %= 2 " + (i %= 2)); // Casting : If no magnitude is lost casting happens automatically, but otherwise it must be done // like this double pi = 3.14; int intPi = (int)pi; // put the data type to convert to between braces // Math Functions // Acos, Asin, Atan, Atan2, Cos, Cosh, Exp, Log, Sin, Sinh, Tan, Tanh double number1 = 10.5; double number2 = 15; Console.WriteLine("Math.Abs(number1) " + (Math.Abs(number1))); Console.WriteLine("Math.Ceiling(number1) " + (Math.Ceiling(number1))); Console.WriteLine("Math.Floor(number1) " + (Math.Floor(number1))); Console.WriteLine("Math.Max(number1, number2) " + (Math.Max(number1, number2))); Console.WriteLine("Math.Min(number1, number2) " + (Math.Min(number1, number2))); Console.WriteLine("Math.Pow(number1, 2) " + (Math.Pow(number1, 2))); Console.WriteLine("Math.Round(number1) " + (Math.Round(number1))); Console.WriteLine("Math.Sqrt(number1) " + (Math.Sqrt(number1))); // Random Numbers Random rand = new Random(); Console.WriteLine("Random Number Between 1 and 10 " + (rand.Next(1, 11))); // ---------- CONDITIONALS ---------- // Relational Operators : > < >= <= == != // Logical Operators : && || ^ ! // If Statement int age = 17; if ((age >= 5) && (age <= 7)) { Console.WriteLine("Go to elementary school"); } else if ((age > 7) && (age < 13)) { Console.WriteLine("Go to middle school"); } else { Console.WriteLine("Go to high school"); } if ((age < 14) || (age > 67)) { Console.WriteLine("You shouldn't work"); } Console.WriteLine("! true = " + (!true)); // Ternary Operator bool canDrive = age >= 16 ? true : false; // Switch is used when you have limited options // Fall through isn't allowed with C# unless there are no statements between cases // You can't check multiple values at once switch (age) { case 0: Console.WriteLine("Infant"); break; case 1: case 2: Console.WriteLine("Toddler"); // Goto can be used to jump to a label elsewhere in the code goto Cute; default: Console.WriteLine("Child"); break; } // Lable we can jump to with Goto Cute: Console.WriteLine("Toddlers are cute"); // ---------- LOOPING ---------- int i = 0; while (i < 10) { // If i = 7 then skip the rest of the code and start with i = 8 if (i == 7) { i++; continue; } // Jump completely out of the loop if i = 9 if (i == 9) { break; } // You can't convert an int into a bool : Print out only odds if ((i % 2) > 0) { Console.WriteLine(i); } i++; } // The do while loop will go through the loop at least once string guess; do { Console.WriteLine("Guess a Number "); guess = Console.ReadLine(); } while (!guess.Equals("15")); // How to check String equality // Puts all changes to the iterator in one place for (int j = 0; j < 10; j++) { if ((j % 2) > 0) { Console.WriteLine(j); } } // foreach cycles through every item in an array or collection string randStr = "Here are some random characters"; foreach (char c in randStr) { Console.WriteLine(c); } // ---------- STRINGS ---------- // Escape Sequences : \' \" \\ \b \n \t string sampString = "A bunch of random words"; // Check if empty Console.WriteLine("Is empty " + String.IsNullOrEmpty(sampString)); Console.WriteLine("Is empty " + String.IsNullOrWhiteSpace(sampString)); Console.WriteLine("String Length " + sampString.Length); // Find a string index (Starts with 0) Console.WriteLine("Index of bunch " + sampString.IndexOf("bunch")); // Get a substring Console.WriteLine("2nd Word " + sampString.Substring(2, 6)); string sampString2 = "More random words"; // Are strings equal Console.WriteLine("Strings equal " + sampString.Equals(sampString2)); // Compare strings Console.WriteLine("Starts with A bunch " + sampString.StartsWith("A bunch")); Console.WriteLine("Ends with words " + sampString.EndsWith("words")); // Trim white space at beginning and end or (TrimEnd / TrimStart) sampString = sampString.Trim(); // Replace words or characters sampString = sampString.Replace("words", "characters"); Console.WriteLine(sampString); // Remove starting at a defined index up to the second index sampString = sampString.Remove(0, 2); Console.WriteLine(sampString); // Join values in array and save to string string[] names = new string[3] { "Matt", "Joe", "Paul" }; Console.WriteLine("Name List " + String.Join(", ", names)); // Formatting : Currency, Decimal Places, Before Decimals, Thousands Separator string fmtStr = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 1.56, 15.567, .56, 1000); Console.WriteLine(fmtStr.ToString()); // ---------- STRINGBUILDER ---------- // Each time you create a string you actually create another string in memory // StringBuilders are used when you want to be able to edit a string without creating new ones StringBuilder sb = new StringBuilder(); // Append a string to the StringBuilder (AppendLine also adds a newline at the end) sb.Append("This is the first sentence."); // Append a formatted string sb.AppendFormat("My name is {0} and I live in {1}", "Derek", "Pennsylvania"); // Clear the StringBuilder // sb.Clear(); // Replaces every instance of the first with the second sb.Replace("a", "e"); // Remove characters starting at the index and then up to the defined index sb.Remove(5, 7); // Out put everything Console.WriteLine(sb.ToString()); // ---------- ARRAYS ---------- // Declare an array int[] randNumArray; // Declare the number of items an array can contain int[] randArray = new int[5]; // Declare and initialize an array int[] randArray2 = { 1, 2, 3, 4, 5 }; // Get array length Console.WriteLine("Array Length " + randArray2.Length); // Get item at index Console.WriteLine("Item 0 " + randArray2[0]); // Cycle through array for (int i = 0; i < randArray2.Length; i++) { Console.WriteLine("{0} : {1}", i, randArray2[i]); } // Cycle with foreach foreach (int num in randArray2) { Console.WriteLine(num); } // Get the index of an item or -1 Console.WriteLine("Where is 1 " + Array.IndexOf(randArray2, 1)); string[] names = { "Tom", "Paul", "Sally" }; // Join an array into a string string nameStr = string.Join(", ", names); Console.WriteLine(nameStr); // Split a string into an array string[] nameArray = nameStr.Split(','); // Create a multidimensional array int[,] multArray = new int[5, 3]; // Create and initialize a multidimensional array int[,] multArray2 = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; // Cycle through multidimensional array foreach (int num in multArray2) { Console.WriteLine(num); } // Cycle and have access to indexes for (int x = 0; x < multArray2.GetLength(0); x += 1) { for (int y = 0; y < multArray2.GetLength(1); y += 1) { Console.WriteLine("{0} | {1} : {2}", x, y, multArray2[x, y]); } } // ---------- LISTS ---------- // A list unlike an array automatically resizes // Create a list and add values List <int> numList = new List <int>(); numList.Add(5); numList.Add(15); numList.Add(25); // Add an array to a list int[] randArray = { 1, 2, 3, 4, 5 }; numList.AddRange(randArray); // Clear a list // numList.Clear(); // Copy an array into a List List <int> numList2 = new List <int>(randArray); // Create a List with array List <int> numList3 = new List <int>(new int[] { 1, 2, 3, 4 }); // Insert in a specific index numList.Insert(1, 10); // Remove a specific value numList.Remove(5); // Remove at an index numList.RemoveAt(2); // Cycle through a List with foreach or for (int i = 0; i < numList.Count; i++) { Console.WriteLine(numList[i]); } // Return the index for a value or -1 Console.WriteLine("4 is in index " + numList3.IndexOf(4)); // Does the List contain a value Console.WriteLine("5 in list " + numList3.Contains(5)); // Search for a value in a string List List <string> strList = new List <string>(new string[] { "Tom", "Paul" }); Console.WriteLine("Tom in list " + strList.Contains("tom", StringComparer.OrdinalIgnoreCase)); // Sort the List strList.Sort(); // ---------- EXCEPTION HANDLING ---------- // All the exceptions // msdn.microsoft.com/en-us/library/system.systemexception.aspx#inheritanceContinued try { Console.Write("Divide 10 by "); int num = int.Parse(Console.ReadLine()); Console.WriteLine("10 / {0} = {1}", num, (10 / num)); } // Specifically catches the divide by zero exception catch (DivideByZeroException ex) { Console.WriteLine("Can't divide by zero"); // Get additonal info on the exception Console.WriteLine(ex.GetType().Name); Console.WriteLine(ex.Message); // Throw the exception to the next inline // throw ex; // Throw a specific exception throw new InvalidOperationException("Operation Failed", ex); } // Catches any other exception catch (Exception ex) { Console.WriteLine("An error occurred"); Console.WriteLine(ex.GetType().Name); Console.WriteLine(ex.Message); } // ---------- CLASSES & OBJECTS ---------- Animal bulldog = new Animal(13, 50, "Spot", "Woof"); Console.WriteLine("{0} says {1}", bulldog.name, bulldog.sound); // Console.WriteLine("No. of Animals " + Animal.getNumOfAnimals()); // ---------- ENUMS ---------- Temperature micTemp = Temperature.Low; Console.Write("What Temp : "); Console.ReadLine(); switch (micTemp) { case Temperature.Freeze: Console.WriteLine("Temp on Freezing"); break; case Temperature.Low: Console.WriteLine("Temp on Low"); break; case Temperature.Warm: Console.WriteLine("Temp on Warm"); break; case Temperature.Boil: Console.WriteLine("Temp on Boil"); break; } // ---------- STRUCTS ---------- Customers bob = new Customers(); bob.createCust("Bob", 15.50, 12345); bob.showCust(); // ---------- ANONYMOUS METHODS ---------- // An anonymous method has no name and its return type is defined by the return used in the method GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5 + 10 = " + sum(5, 10)); // ---------- LAMBDA EXPRESSIONS ---------- // A lambda expression is used to act as an anonymous function or expression tree // You can assign the lambda expression to a function instance Func <int, int, int> getSum = (x, y) => x + y; Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3)); // Get odd numbers from a list List <int> numList = new List <int> { 5, 10, 15, 20, 25 }; // With an Expression Lambda the input goes in the left (n) and the statements go on the right List <int> oddNums = numList.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.Write(num + ", "); } // ---------- FILE I/O ---------- // The StreamReader and StreamWriter allows you to create text files while reading and // writing to them string[] custs = new string[] { "Tom", "Paul", "Greg" }; using (StreamWriter sw = new StreamWriter("custs.txt")) { foreach (string cust in custs) { sw.WriteLine(cust); } } string custName = ""; using (StreamReader sr = new StreamReader("custs.txt")) { while ((custName = sr.ReadLine()) != null) { Console.WriteLine(custName); } } Console.Write("Hit Enter to Exit"); string exitApp = Console.ReadLine(); }
static void Main(string[] args) { GetSum sum = delegate(double num1, double num2) { return(num1 + num2); }; Console.WriteLine("5+10= " + sum(5, 10)); // // lambda expression Func <int, int, int> getTot = (x, y) => x + y; Console.WriteLine("10+345= " + getTot.Invoke(10, 345)); // // List // List <int> numList = new List <int> { 5, 10, 15, 20, 25, 30 }; List <int> oddNums = numList.Where(n => n % 2 == 1).ToList(); foreach (int num in oddNums) { Console.WriteLine(num + ","); } // // Write and Read with file // string[] custs = new string[] { "Tom", "Paul", "Greg", "Peter" }; using (StreamWriter sw = new StreamWriter("custs.txt")) { foreach (string cust in custs) { sw.WriteLine(cust); } } string custName = ""; using (StreamReader sr = new StreamReader("custs.txt")) { while ((custName = sr.ReadLine()) != null) { Console.WriteLine(custName); } } // // // Customers customer = new Customers(); customer.createCust("smith", 1232.40, 343432); customer.showCust(); Temperature micTemp = Temperature.Warm; switch (micTemp) { case Temperature.Freeze: Console.WriteLine("Temp on Freezing"); break; case Temperature.Low: Console.WriteLine("Temp on Low"); break; case Temperature.Warm: Console.WriteLine("Temp on Warm"); break; case Temperature.Boil: Console.WriteLine("Temp on Boil"); break; } Animal spot = new Animal(15, 10, "spot", "woof"); Console.WriteLine("{0} says {1}", spot.name, spot.sound); Console.WriteLine("Number of animals " + Animal.getNumOfAnimals()); Console.WriteLine(spot.toString()); Console.WriteLine(spot.getSum(num2: 1.4, num1: 2.7)); Animal grover = new Animal { name = "Grover", height = 16, weight = 18, sound = "Grrr" }; //============================== Dog spike = new Dog(); Console.WriteLine(spike.toString()); spike = new Dog(20, 15, "Spike", "Grrrrrr", "Chicken"); Console.WriteLine(spike.toString()); //============================== Shape rect = new Rectangle(5, 7); Shape tri = new Triangle(3, 4); Console.WriteLine("Rect Area " + rect.area()); Console.WriteLine("Tri Area " + tri.area()); Rectangle combRect = new Rectangle(5, 6) + new Rectangle(7, 8); Console.WriteLine("combRect Area " + combRect.area()); //============================== KeyValue <string, string> superman = new KeyValue <string, string>("", ""); superman.key = "superman"; superman.value = "Clark Kent"; KeyValue <int, string> samsungTV = new KeyValue <int, string>(0, ""); samsungTV.key = 342; samsungTV.value = "a 50 inch samsung TV"; superman.showData(); samsungTV.showData(); Console.ReadLine(); }