├── C# Code 1 └── Program.cs ├── C# Code 10 └── Program.cs ├── C# Code 11 ├── Animal.cs ├── AnimalFarm.cs ├── Box.cs └── Program.cs ├── C# Code 12 ├── Animal.cs ├── Owner.cs └── Program.cs ├── C# Code 13 ├── BankAcct.cs └── Program.cs ├── C# Code 14 └── Program.cs ├── C# Code 15 ├── Animal.cs └── Program.cs ├── C# Code 16 └── Program.cs ├── C# Code 17 ├── MainWindow.xaml └── MainWindow.xaml.cs ├── C# Code 2 ├── Animal.cs ├── Program.cs └── ShapeMath.cs ├── C# Code 3 ├── Animal.cs └── Program.cs ├── C# Code 4 ├── Animal.cs ├── AnimalIDInfo.cs ├── Dog.cs └── Program.cs ├── C# Code 5 ├── Circle.cs ├── Program.cs ├── Rectangle.cs └── Shape.cs ├── C# Code 6 ├── ICommand.cs ├── IDrivable.cs ├── IElectronicDevice.cs ├── PowerButton.cs ├── Program.cs ├── TVRemote.cs ├── Television.cs └── Vehicle.cs ├── C# Code 7 ├── Battle.cs ├── CanTeleport.cs ├── CantTeleport.cs ├── MagicWarrior.cs ├── Program.cs ├── Teleports.cs └── Warrior.cs ├── C# Code 8 └── Program.cs ├── C# Code 9 ├── Animal.cs └── Program.cs └── README.md /C# Code 1/Program.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Import namespace called system that has many classes 3 | and useful functions (Without it we'd have to type 4 | System.Console.Write) 5 | */ 6 | using System; 7 | using System.Globalization; 8 | using System.Text; 9 | 10 | // Change interface size : Tools -> Options -> 11 | // Environment -> Fonts and Colors -> Environment 12 | 13 | // Defines our namespace is HelloWorld 14 | namespace HelloWorld { 15 | // Our class name is Program 16 | public class Program 17 | { 18 | 19 | // ------ FUNCTIONS ------ 20 | 21 | static void PrintArray(int[] intArray, string mess) 22 | { 23 | foreach (int k in intArray) 24 | { 25 | Console.WriteLine("{0} : {1} ", mess, k); 26 | } 27 | } 28 | 29 | private static bool GT10(int val) 30 | { 31 | return val > 10; 32 | } 33 | 34 | static double DoDivision(double x, double y) 35 | { 36 | if (y == 0) 37 | { 38 | // We are throwing an exception because 39 | // you can't divide by zero 40 | throw new System.DivideByZeroException(); 41 | } 42 | return x / y; 43 | } 44 | 45 | private static void SayHello() 46 | { 47 | // Defines a variable that will store a string 48 | // of characters 49 | string name = ""; 50 | 51 | Console.Write("What is your name : "); 52 | 53 | // Save the input the user provides 54 | name = Console.ReadLine(); 55 | 56 | Console.WriteLine("Hello {0}", name); 57 | } 58 | 59 | // If you assign a value then it is optional to 60 | // pass 61 | static double GetSum(double x = 1, double y = 1) 62 | { 63 | double temp = x; 64 | x = y; 65 | y = temp; 66 | return x + y; 67 | } 68 | 69 | // ----- OUT PARAMETER ----- 70 | // A parameter marked with out must be assigned 71 | // a value in the method 72 | static void DoubleIt(int x, out int solution) 73 | { 74 | solution = x * 2; 75 | } 76 | 77 | // ----- PASS BY REFERENCE ----- 78 | // If a variable is passed by reference changes 79 | // to its value in the method effect it outside 80 | // of the method 81 | public static void Swap(ref int num3, ref int num4) 82 | { 83 | int temp = num3; 84 | num3 = num4; 85 | num4 = temp; 86 | } 87 | 88 | // ----- PARAMS ----- 89 | // The params array must be the last parameter 90 | // in the list 91 | static double GetSumMore(params double[] nums) 92 | { 93 | double sum = 0; 94 | foreach (int i in nums) 95 | { 96 | sum += i; 97 | } 98 | return sum; 99 | } 100 | 101 | // ----- NAMED PARAMETERS ----- 102 | static void PrintInfo(string name, int zipCode) 103 | { 104 | Console.WriteLine("{0} lives in the zip code {1}", name, zipCode); 105 | } 106 | 107 | // ----- METHOD OVERLOADING ----- 108 | static double GetSum2(double x = 1, double y = 1) 109 | { 110 | return x + y; 111 | } 112 | 113 | static double GetSum2(string x = "1", string y = "1") 114 | { 115 | double dblX = Convert.ToDouble(x); 116 | double dblY = Convert.ToDouble(y); 117 | return dblX + dblY; 118 | } 119 | 120 | static void PaintCar(CarColor cc) 121 | { 122 | Console.WriteLine("The car was painted {0} with the code {1}", 123 | cc, (int)cc); 124 | } 125 | 126 | // ------ END OF FUNCTIONS ------ 127 | 128 | // ------ ENUMS ------ 129 | // An enum is a custom data type with 130 | // key value pairs. They allow you to 131 | // use symbolic names to represent data 132 | // The first number is 0 by default unless 133 | // you change it 134 | // You can define the underlying type 135 | // or leave it as int as default 136 | 137 | enum CarColor : byte 138 | { 139 | Orange = 1, 140 | Blue, 141 | Green, 142 | Red, 143 | Yellow 144 | } 145 | 146 | // Execution begins in the main function 147 | // static means this function can run without 148 | // creating an object 149 | // void means that this function doesn't return a value 150 | // args represent data that can be passed to our program 151 | // from the command line as an array of strings 152 | static void Main(string[] args) 153 | { 154 | // Prints Hello World on the console 155 | Console.WriteLine("Hello World!"); 156 | 157 | // ------ CONSOLE METHODS ----- 158 | // Change the text color in the console 159 | // Console.ForegroundColor = ConsoleColor.Black; 160 | 161 | // Change background color 162 | // Console.BackgroundColor = ConsoleColor.White; 163 | 164 | // Set background for whole console 165 | // Console.Clear(); 166 | 167 | // Outputs text without a newline 168 | Console.Write("What is your name? "); 169 | 170 | // Stores data entered by user in name 171 | string name = Console.ReadLine(); 172 | 173 | // Outputs Hello + value stored in name 174 | Console.WriteLine($"Hello {name}"); 175 | 176 | // ------ VARIABLES ------ 177 | // Used to store different types of data 178 | 179 | // Bools store true or false 180 | bool canIVote = true; 181 | 182 | // INTEGERS 183 | // Integers are 32-bit signed integers 184 | Console.WriteLine("Biggest Integer : {0}", int.MaxValue); 185 | Console.WriteLine("Smallest Integer : {0}", int.MinValue); 186 | 187 | // LONGS 188 | // Longs are 64-bit signed integers 189 | Console.WriteLine("Biggest Long : {0}", long.MaxValue); 190 | Console.WriteLine("Smallest Long : {0}", long.MinValue); 191 | 192 | // DECIMALS 193 | // Decimals store 128-bit precise decimal values 194 | // It is accurate to 28 digits 195 | decimal decPiVal = 3.1415926535897932384626433832M; 196 | decimal decBigNum = 3.00000000000000000000000000011M; 197 | Console.WriteLine("DEC : PI + bigNum = {0}", decPiVal + decBigNum); 198 | 199 | Console.WriteLine("Biggest Decimal : {0}", Decimal.MaxValue); 200 | 201 | // DOUBLES 202 | // Doubles are 64-bit float types 203 | Console.WriteLine("Biggest Double : {0}", Double.MaxValue); 204 | 205 | // It is precise to 14 digits 206 | double dblPiVal = 3.14159265358979; 207 | double dblBigNum = 3.00000000000002; 208 | Console.WriteLine("DBL : PI + bigNum = {0}", dblPiVal + dblBigNum); 209 | 210 | // FLOATS 211 | // Floats are 32-bit float types 212 | Console.WriteLine("Biggest Float : {0}", float.MaxValue.ToString("#")); 213 | 214 | // It is precise to 6 digits 215 | float fltPiVal = 3.141592F; 216 | float fltBigNum = 3.000002F; 217 | Console.WriteLine("FLT : PI + bigNum = {0}", fltPiVal + fltBigNum); 218 | 219 | // Other Data Types 220 | // byte : 8-bit unsigned int 0 to 255 221 | // char : 16-bit unicode character 222 | // sbyte : 8-bit signed int 128 to 127 223 | // short : 16-bit signed int -32,768 to 32,767 224 | // uint : 32-bit unsigned int 0 to 4,294,967,295 225 | // ulong : 64-bit unsigned int 0 to 18,446,744,073,709,551,615 226 | // ushort : 16-bit unsigned int 0 to 65,535 227 | 228 | // ---------- DATA TYPE CONVERSION ---------- 229 | 230 | // You can convert from string to other types with Parse 231 | bool boolFromStr = bool.Parse("True"); 232 | int intFromStr = int.Parse("100"); 233 | double dblFromStr = double.Parse("1.234"); 234 | 235 | // Convert double into a string 236 | string strVal = dblFromStr.ToString(); 237 | 238 | // Get the new data type 239 | Console.WriteLine($"Data type : {strVal.GetType()}"); 240 | 241 | // Cast double into integer (Explicit Conversion) 242 | // Put the data type to convert into between () 243 | double dblNum = 12.345; 244 | Console.WriteLine($"Integer : {(int)dblNum}"); 245 | 246 | // Cast integer into long (Implicit Conversion) 247 | // smaller size type to a larger size 248 | int intNum = 10; 249 | long longNum = intNum; 250 | 251 | // ---------- FORMATTING OUTPUT ---------- 252 | 253 | // Format output for currency 254 | Console.WriteLine("Currency : {0:c}", 23.455); 255 | 256 | // Pad with zeroes 257 | Console.WriteLine("Pad with 0s : {0:d4}", 23); 258 | 259 | // Define decimals 260 | Console.WriteLine("3 Decimals : {0:f3}", 23.4555); 261 | 262 | // Add commas and decimals 263 | Console.WriteLine("Commas : {0:n4}", 2300); 264 | 265 | // ---------- STRINGS ---------- 266 | // Strings store a series of characters 267 | string randString = "This is a string"; 268 | 269 | // Get number of characters in string 270 | Console.WriteLine("String Length : {0}", randString.Length); 271 | 272 | // Check if string contains other string 273 | Console.WriteLine("String Contains is : {0}", 274 | randString.Contains("is")); 275 | 276 | // Index of string match 277 | Console.WriteLine("Index of is : {0}", 278 | randString.IndexOf("is")); 279 | 280 | // Remove number of characters starting at an index 281 | Console.WriteLine("Remove string : {0}", 282 | randString.Remove(10, 6)); 283 | 284 | // Add a string starting at an index 285 | Console.WriteLine("Insert String : {0}", 286 | randString.Insert(10, "short ")); 287 | 288 | // Replace a string with another 289 | Console.WriteLine("Replace String : {0}", 290 | randString.Replace("string", "sentence")); 291 | 292 | // Compare strings and ignore case 293 | // < 0 : str1 preceeds str2 294 | // = : Zero 295 | // > 0 : str2 preceeds str1 296 | Console.WriteLine("Compare A to B : {0}", 297 | String.Compare("A", "B", StringComparison.OrdinalIgnoreCase)); 298 | 299 | // Check if strings are equal 300 | Console.WriteLine("A = a : {0}", 301 | String.Equals("A", "a", StringComparison.OrdinalIgnoreCase)); 302 | 303 | // Add padding left 304 | Console.WriteLine("Pad Left : {0}", 305 | randString.PadLeft(20, '.')); 306 | 307 | // Add padding right 308 | Console.WriteLine("Pad Right : {0} Stuff", 309 | randString.PadRight(20, '.')); 310 | 311 | // Trim whitespace 312 | Console.WriteLine("Trim : {0}", 313 | randString.Trim()); 314 | 315 | // Make uppercase 316 | Console.WriteLine("Uppercase : {0}", 317 | randString.ToUpper()); 318 | 319 | // Make lowercase 320 | Console.WriteLine("Lowercase : {0}", 321 | randString.ToLower()); 322 | 323 | // Use Format to create strings 324 | string newString = String.Format("{0} saw a {1} {2} in the {3}", 325 | "Paul", "rabbit", "eating", "field"); 326 | 327 | // You can add newlines with \n and join strings with + 328 | Console.Write(newString + "\n"); 329 | 330 | // Other escape characters 331 | // \' \" \\ \t \a 332 | 333 | // Verbatim strings ignore escape characters 334 | Console.WriteLine(@"Exactly What I Typed\n"); 335 | 336 | // ------ ARRAYS ------ 337 | // Arrays are just boxes inside of a bigger box 338 | // that can contain many values of the same 339 | // data type 340 | // Each item is assigned a key starting at 0 341 | // and incrementing up from there 342 | 343 | // Define an array which holds 3 values 344 | // Arrays have fixed sizes 345 | int[] favNums = new int[3]; 346 | 347 | // Add a value to the array 348 | favNums[0] = 23; 349 | 350 | // Retrieve a value 351 | Console.WriteLine("favNum 0 : {0}", favNums[0]); 352 | 353 | // Create and fill array 354 | string[] customers = { "Bob", "Sally", "Sue" }; 355 | 356 | // You can use var to create arrays, but the 357 | // values must be of the same type 358 | var employees = new[] { "Mike", "Paul", "Rick" }; 359 | 360 | // Create an array of base objects which is the 361 | // base type of all other types 362 | object[] randomArray = { "Paul", 45, 1.234 }; 363 | 364 | // GetType knows its true type 365 | Console.WriteLine("randomArray 0 : {0}", 366 | randomArray[0].GetType()); 367 | 368 | // Get number of items in array 369 | Console.WriteLine("Array Size : {0}", 370 | randomArray.Length); 371 | 372 | // Use for loop to cycle through the array 373 | for (int j = 0; j < randomArray.Length; j++) 374 | { 375 | Console.WriteLine("Array {0} : Value : {1}", 376 | j, randomArray[j]); 377 | } 378 | 379 | // Multidimensional arrays 380 | // When you define an array like arrName[5] you 381 | // are saying you want to create boxes stacked 382 | // vertically 383 | 384 | // If you define arrName[2,2] you are saying 385 | // you want to have 2 rows high and 2 across 386 | string[,] custNames = new string[2, 2] { { "Bob", "Smith" }, 387 | { "Sally", "Smith" } }; 388 | 389 | // Get value in MD array 390 | Console.WriteLine("MD Value : {0}", 391 | custNames.GetValue(1, 1)); 392 | 393 | // Cycle through the multidimensional array 394 | // Get length of multidimensional array column 395 | for (int j = 0; j < custNames.GetLength(0); j++) 396 | { 397 | // Get length of multidimensional array row 398 | for (int k = 0; k < custNames.GetLength(1); k++) 399 | { 400 | Console.Write("{0} ", custNames[j, k]); 401 | } 402 | Console.WriteLine(); 403 | } 404 | 405 | // An array like arrName[2,2,3] would be like a 406 | // stack of 3 spread sheets with 2 rows and 2 407 | // columns worth of data on each page 408 | 409 | // foreach can be used to cycle through an array 410 | int[] randNums = { 1, 4, 9, 2 }; 411 | 412 | // You can pass an array to a function 413 | PrintArray(randNums, "ForEach"); 414 | 415 | // Sort array 416 | Array.Sort(randNums); 417 | 418 | // Reverse array 419 | Array.Reverse(randNums); 420 | 421 | // Get index of match or return -1 422 | Console.WriteLine("1 at index : {0} ", 423 | Array.IndexOf(randNums, 1)); 424 | 425 | // Change value at index 1 to 0 426 | randNums.SetValue(0, 1); 427 | 428 | // Copy part of an array to another 429 | int[] srcArray = { 1, 2, 3 }; 430 | int[] destArray = new int[2]; 431 | int startInd = 0; 432 | int length = 2; 433 | 434 | Array.Copy(srcArray, startInd, destArray, 435 | startInd, length); 436 | 437 | PrintArray(destArray, "Copy"); 438 | 439 | // Create an array with CreateInstance 440 | Array anotherArray = Array.CreateInstance(typeof(int), 10); 441 | 442 | // Copy values in srcArray to destArray starting 443 | // at index 5 in destination 444 | srcArray.CopyTo(anotherArray, 5); 445 | 446 | foreach (int m in anotherArray) 447 | { 448 | Console.WriteLine("CopyTo : {0} ", m); 449 | } 450 | 451 | // ----- IF / ELSE / ----- 452 | // Relational Operators : > < >= <= == != 453 | // Logical Operators : && || ! 454 | 455 | int age = 17; 456 | 457 | if ((age >= 5) && (age <= 7)) 458 | { 459 | Console.WriteLine("Go to elementary school"); 460 | } 461 | else if ((age > 7) && (age < 13)) 462 | { 463 | Console.WriteLine("Go to middle school"); 464 | } 465 | else if ((age > 13) && (age < 19)) 466 | { 467 | Console.WriteLine("Go to high school"); 468 | } 469 | else 470 | { 471 | Console.WriteLine("Go to college"); 472 | } 473 | 474 | if ((age < 14) || (age > 67)) 475 | { 476 | Console.WriteLine("You shouldn't work"); 477 | } 478 | 479 | Console.WriteLine("! true = " + (!true)); 480 | 481 | // Ternary Operator 482 | // Assigns the 1st value if true and otherwise 483 | // the 2nd 484 | bool canDrive = age >= 16 ? true : false; 485 | 486 | // Switch is used when you have limited options 487 | // The only way to use ranges is to stack 488 | // the possible values 489 | switch (age) 490 | { 491 | case 1: 492 | case 2: 493 | Console.WriteLine("Go to Day Care"); 494 | break; 495 | case 3: 496 | case 4: 497 | Console.WriteLine("Go to Preschool"); 498 | break; 499 | case 5: 500 | Console.WriteLine("Go to Kindergarten"); 501 | break; 502 | default: 503 | Console.WriteLine("Go to another school"); 504 | // You can also jump out of a switch 505 | // with goto 506 | goto OtherSchool; 507 | } 508 | 509 | OtherSchool: 510 | Console.WriteLine("Elementary, Middle, High School"); 511 | 512 | // To compare strings use Equals 513 | string name2 = "Derek"; 514 | string name3 = "Derek"; 515 | 516 | if (name2.Equals(name3, StringComparison.Ordinal)) 517 | { 518 | Console.WriteLine("Names are Equal"); 519 | } 520 | 521 | // ----- WHILE LOOP ----- 522 | // You use the while loop when you want to execute 523 | // as long as a condition is true 524 | 525 | // This while loop will print odd numbers between 526 | // 1 and 10 527 | int i = 1; 528 | while (i <= 10) 529 | { 530 | // % (Modulus) returns the remainder of a 531 | // division. If it returns 0 that means the 532 | // value is even 533 | if (i % 2 == 0) 534 | { 535 | i++; 536 | 537 | // Continue skips the rest of the code and 538 | // starts execution back at the top of the 539 | // while 540 | continue; 541 | } 542 | 543 | // Break jumps completely out of the loop 544 | if (i == 9) break; 545 | 546 | Console.WriteLine(i); 547 | i++; 548 | } 549 | 550 | // ----- DO WHILE LOOP ----- 551 | // Use do while when you must execute the code 552 | // at least once 553 | 554 | // Generate a random number 555 | Random rnd = new Random(); 556 | int secretNumber = rnd.Next(1, 11); 557 | int numberGuessed = 0; 558 | Console.WriteLine("Random Num : ", secretNumber); 559 | 560 | do 561 | { 562 | Console.Write("Enter a number between 1 & 10 : "); 563 | 564 | // Use Convert to switch the string into an int 565 | // Other Convert options : ToBoolean, ToByte, 566 | // ToChar, ToDecimal, ToDouble, ToInt64, 567 | // ToString, and they can convert from any 568 | // type to any other type 569 | numberGuessed = Convert.ToInt32(Console.ReadLine()); 570 | 571 | } while (secretNumber != numberGuessed); 572 | 573 | Console.WriteLine("You guessed it is was {0}", 574 | secretNumber); 575 | 576 | 577 | // ----- EXCEPTION HANDLING ----- 578 | // We use exception handling to catch errors 579 | // that could crash our program 580 | double num1 = 5; 581 | double num2 = 0; 582 | 583 | // Code that could cause an error is surrounded 584 | // by a try block 585 | try 586 | { 587 | Console.WriteLine("5 / 0 = {0}", 588 | DoDivision(num1, num2)); 589 | } 590 | 591 | // We catch the error and warn the user 592 | // rather then crash the program 593 | catch (DivideByZeroException ex) 594 | { 595 | Console.WriteLine("You can't Divide by Zero"); 596 | 597 | // Get additonal info on the exception 598 | Console.WriteLine(ex.GetType().Name); 599 | Console.WriteLine(ex.Message); 600 | 601 | } 602 | 603 | // This is the default catch all for exceptions 604 | catch (Exception ex) 605 | { 606 | Console.WriteLine("An error occurred"); 607 | Console.WriteLine(ex.GetType().Name); 608 | Console.WriteLine(ex.Message); 609 | } 610 | 611 | // finally always runs and provides for clean up 612 | finally 613 | { 614 | Console.WriteLine("Cleaning Up"); 615 | } 616 | 617 | // ----- STRINGBUILDER ----- 618 | // Each time you change a string you are actually 619 | // creating a new string which is inefficient 620 | // when you are working with large blocks of text 621 | // StringBuilders actually change the text 622 | // rather then make a copy 623 | 624 | // Create a StringBuilder with a default size 625 | // of 16 characters, but it grows automatically 626 | StringBuilder sb = new StringBuilder("Random Text"); 627 | 628 | // Create a StringBuilder with a size of 256 629 | StringBuilder sb2 = new StringBuilder("More Stuff that is very important", 256); 630 | 631 | // Get max size 632 | Console.WriteLine("Capacity : {0}", sb2.Capacity); 633 | 634 | // Get length 635 | Console.WriteLine("Length : {0}", sb2.Length); 636 | 637 | // Add text to StringBuilder 638 | sb2.AppendLine("\nMore important text"); 639 | 640 | // Define culture specific formating 641 | CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US"); 642 | 643 | // Append a format string 644 | string bestCust = "Bob Smith"; 645 | sb2.AppendFormat(enUS, "Best Customer : {0}", bestCust); 646 | 647 | // Output StringBuilder 648 | Console.WriteLine(sb2.ToString()); 649 | 650 | // Replace a string 651 | sb2.Replace("text", "characters"); 652 | Console.WriteLine(sb2.ToString()); 653 | 654 | // Clear a string builder 655 | sb2.Clear(); 656 | 657 | sb2.Append("Random Text"); 658 | 659 | // Are objects equal 660 | Console.WriteLine(sb.Equals(sb2)); 661 | 662 | // Insert at an index 663 | sb2.Insert(11, " that's Great"); 664 | 665 | Console.WriteLine("Insert : {0}", sb2.ToString()); 666 | 667 | // Remove number of characters starting at index 668 | sb2.Remove(11, 7); 669 | 670 | Console.WriteLine("Remove : {0}", sb2.ToString()); 671 | 672 | // ---------- FUNCTIONS / METHODS ---------- 673 | // Functions are used to avoid code duplication, provides 674 | // organization and allows use to simulate different 675 | // systems 676 | // (Parameters) 677 | // { } 678 | 679 | // Access Specifier determines whether the function can 680 | // be called from another class 681 | // public : Can be accessed from another class 682 | // private : Can't be accessed from another class 683 | // protected : Can be accessed by class and derived classes 684 | 685 | SayHello(); 686 | 687 | // ----- PASSING BY VALUE ----- 688 | // By default values are passed into a method 689 | // and not a reference to the variable passed 690 | // Changes made to those values do not effect the 691 | // variables outside of the method 692 | double x = 5; 693 | double y = 4; 694 | 695 | Console.WriteLine("5 + 4 = {0}", 696 | GetSum(x, y)); 697 | 698 | // Even though the value for x changed in 699 | // method it remains unchanged here 700 | Console.WriteLine("x = {0}", 701 | x); 702 | 703 | // ----- OUT PARAMETER ----- 704 | // You can pass a variable as an output 705 | // variable even without assigning a 706 | // value to it 707 | int solution; 708 | 709 | // A parameter passed with out has its 710 | // value assigned in the method 711 | DoubleIt(15, out solution); 712 | 713 | Console.WriteLine("15 * 2 = {0}", 714 | solution); 715 | 716 | // ----- PASS BY REFERENCE ----- 717 | int num3 = 10; 718 | int num4 = 20; 719 | 720 | Console.WriteLine("Before Swap num1 : {0} num2 : {1}", num3, num4); 721 | 722 | Swap(ref num3, ref num4); 723 | 724 | Console.WriteLine("After Swap num1 : {0} num2 : {1}", num1, num2); 725 | 726 | // ----- PARAMS ----- 727 | // You are able to pass a variable amount 728 | // of data of the same data type into a 729 | // method using params. You can also pass 730 | // in an array. 731 | Console.WriteLine("1 + 2 + 3 = {0}", 732 | GetSumMore(1, 2, 3)); 733 | 734 | // ----- NAMED PARAMETERS ----- 735 | // You can pass values in any order if 736 | // you used named parameters 737 | PrintInfo(zipCode: 15147, 738 | name: "Derek Banas"); 739 | 740 | // ----- METHOD OVERLOADING ----- 741 | // You can define methods with the same 742 | // name that will be called depending on 743 | // what data is sent automatically 744 | Console.WriteLine("5.0 + 4.0 = {0}", 745 | GetSum2(5.0, 4.5)); 746 | 747 | Console.WriteLine("5 + 4 = {0}", 748 | GetSum2(5, 4)); 749 | 750 | Console.WriteLine("5 + 4 = {0}", 751 | GetSum2("5", "4")); 752 | 753 | 754 | // ---------- DATETIME & TIMESPAN ---------- 755 | 756 | // Used to define dates 757 | DateTime awesomeDate = new DateTime(1974, 12, 21); 758 | Console.WriteLine("Day of Week : {0}", awesomeDate.DayOfWeek); 759 | 760 | // You can change values 761 | awesomeDate = awesomeDate.AddDays(4); 762 | awesomeDate = awesomeDate.AddMonths(1); 763 | awesomeDate = awesomeDate.AddYears(1); 764 | Console.WriteLine("New Date : {0}", awesomeDate.Date); 765 | 766 | // TimeSpan 767 | // Used to define a time 768 | TimeSpan lunchTime = new TimeSpan(12, 30, 0); 769 | 770 | // Change values 771 | lunchTime = lunchTime.Subtract(new TimeSpan(0, 15, 0)); 772 | lunchTime = lunchTime.Add(new TimeSpan(1, 0, 0)); 773 | Console.WriteLine("New Time : {0}", lunchTime.ToString()); 774 | 775 | // ----- ENUM ----- 776 | CarColor car1 = CarColor.Blue; 777 | PaintCar(car1); 778 | 779 | // Waits for input from the user if you run the 780 | // ConsoleApp1.exe instead of instantly closing 781 | // The executable is in bin/Debug/net6.0 782 | Console.Read(); 783 | } 784 | } 785 | } 786 | -------------------------------------------------------------------------------- /C# Code 10/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | 5 | namespace ConsoleApp10 6 | { 7 | // This time I'll cover multiple functions 8 | // you can use to work with lists of data 9 | // including Lambda, Where, ToList, Select, 10 | // Zip, Aggregate and Average 11 | 12 | class Program 13 | { 14 | // Delegate that is assigned a Lambda 15 | // expression 16 | delegate double doubleIt(double val); 17 | 18 | static void Main(string[] args) 19 | { 20 | // Like we did with predicates earlier 21 | // Lambda expressions allow you to 22 | // use anonymous methods that define 23 | // the input parameters on the left 24 | // and the code to execute on the right 25 | 26 | // Assign a Lambda to the delegate 27 | doubleIt dblIt = x => x * 2; 28 | Console.WriteLine($"5 * 2 = {dblIt(5)}"); 29 | 30 | // You don't have to use delegates though 31 | // Here we'll search through a list to 32 | // find all the even numbers 33 | List numList = new List { 1, 9, 2, 6, 3 }; 34 | 35 | // Put the number in the list if the 36 | // condition is true 37 | var evenList = numList.Where(a => a % 2 == 0).ToList(); 38 | 39 | foreach (var j in evenList) 40 | Console.WriteLine(j); 41 | 42 | // Add values in a range to a list 43 | var rangeList = numList.Where(x => (x > 2) || (x < 9)).ToList(); 44 | 45 | foreach (var k in rangeList) 46 | Console.WriteLine(k); 47 | 48 | // Find the number of heads and tails in 49 | // a list 1 = H, 2 = T 50 | 51 | // Generate our list 52 | List flipList = new List(); 53 | int i = 0; 54 | Random rnd = new Random(); 55 | while (i < 100) 56 | { 57 | flipList.Add(rnd.Next(1, 3)); 58 | i++; 59 | } 60 | 61 | // Print out the heads and tails 62 | Console.WriteLine("Heads : {0}", 63 | flipList.Where(a => a == 1).ToList().Count()); 64 | Console.WriteLine("Tails : {0}", 65 | flipList.Where(a => a == 2).ToList().Count()); 66 | 67 | // Find all names starting with s 68 | var nameList = new List { "Doug", "Sally", "Sue" }; 69 | 70 | var sNameList = nameList.Where(x => x.StartsWith("S")); 71 | 72 | foreach (var m in sNameList) 73 | Console.WriteLine(m); 74 | 75 | // ---------- SELECT ---------- 76 | // Select allows us to execute a function 77 | // on each item in a list 78 | 79 | // Generate a list from 1 to 10 80 | var oneTo10 = new List(); 81 | oneTo10.AddRange(Enumerable.Range(1, 10)); 82 | 83 | var squares = oneTo10.Select(x => x * x); 84 | 85 | foreach (var l in squares) 86 | Console.WriteLine(l); 87 | 88 | // ---------- ZIP ---------- 89 | // Zip applies a function to two lists 90 | // Add values in 2 lists together 91 | var listOne = new List(new int[] { 1, 3, 4 }); 92 | var listTwo = new List(new int[] { 4, 6, 8 }); 93 | 94 | var sumList = listOne.Zip(listTwo, (x, y) => x + y).ToList(); 95 | 96 | foreach (var n in sumList) 97 | Console.WriteLine(n); 98 | 99 | // ---------- AGGREGATE ---------- 100 | // Aggregate performs an operation on 101 | // each item in a list and carries the 102 | // results forward 103 | 104 | // Sum values in a list 105 | var numList2 = new List() { 1, 2, 3, 4, 5 }; 106 | Console.WriteLine("Sum : {0}", 107 | numList2.Aggregate((a, b) => a + b)); 108 | 109 | // ---------- AVERAGE ---------- 110 | // Get the average of a list of values 111 | var numList3 = new List() { 1, 2, 3, 4, 5 }; 112 | 113 | // AsQueryable allows you to manipulate the 114 | // collection with the Average function 115 | Console.WriteLine("AVG : {0}", 116 | numList3.AsQueryable().Average()); 117 | 118 | // ---------- ALL ---------- 119 | // Determines if all items in a list 120 | // meet a condition 121 | var numList4 = new List() { 1, 2, 3, 4, 5 }; 122 | 123 | Console.WriteLine("All > 3 : {0}", 124 | numList4.All(x => x > 3)); 125 | 126 | // ---------- ANY ---------- 127 | // Determines if any items in a list 128 | // meet a condition 129 | var numList5 = new List() { 1, 2, 3, 4, 5 }; 130 | 131 | Console.WriteLine("Any > 3 : {0}", 132 | numList5.Any(x => x > 3)); 133 | 134 | // ---------- DISTINCT ---------- 135 | // Eliminates duplicates from a list 136 | var numList6 = new List() { 1, 2, 3, 2, 3 }; 137 | 138 | Console.WriteLine("Distinct : {0}", 139 | string.Join(", ", numList6.Distinct())); 140 | 141 | // ---------- EXCEPT ---------- 142 | // Receives 2 lists and returns values not 143 | // found in the 2nd list 144 | var numList7 = new List() { 1, 2, 3, 2, 3 }; 145 | var numList8 = new List() { 3 }; 146 | 147 | Console.WriteLine("Except : {0}", 148 | string.Join(", ", numList7.Except(numList8))); 149 | 150 | // ---------- INTERSECT ---------- 151 | // Receives 2 lists and returns values that 152 | // both lists have 153 | var numList9 = new List() { 1, 2, 3, 2, 3 }; 154 | var numList10 = new List() { 2, 3 }; 155 | 156 | Console.WriteLine("Intersect : {0}", 157 | string.Join(", ", numList9.Intersect(numList10))); 158 | 159 | } 160 | 161 | } 162 | 163 | } -------------------------------------------------------------------------------- /C# Code 11/Animal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ConsoleApp11 8 | { 9 | class Animal 10 | { 11 | public string Name { get; set; } 12 | 13 | public Animal(string name = "No Name") 14 | { 15 | Name = name; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /C# Code 11/AnimalFarm.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace ConsoleApp11 9 | { 10 | // IEnumerable provides for iteration 11 | // over a collection 12 | class AnimalFarm : IEnumerable 13 | { 14 | // Holds list of Animals 15 | private List animalList = new List(); 16 | 17 | public AnimalFarm(List animalList) 18 | { 19 | this.animalList = animalList; 20 | } 21 | 22 | public AnimalFarm() 23 | { 24 | } 25 | 26 | // Indexer for AnimalFarm created with this[] 27 | public Animal this[int index] 28 | { 29 | get { return (Animal)animalList[index]; } 30 | set { animalList.Insert(index, value); } 31 | } 32 | 33 | // Returns the number of values in the 34 | // collection 35 | public int Count 36 | { 37 | get 38 | { 39 | return animalList.Count; 40 | } 41 | } 42 | 43 | // Returns an enumerator that is used to 44 | // iterate through the collection 45 | IEnumerator IEnumerable.GetEnumerator() 46 | { 47 | return animalList.GetEnumerator(); 48 | } 49 | 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /C# Code 11/Box.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ConsoleApp11 8 | { 9 | class Box 10 | { 11 | public double Length { get; set; } 12 | public double Width { get; set; } 13 | public double Breadth { get; set; } 14 | 15 | public Box() 16 | : this(1, 1, 1) { } 17 | 18 | public Box(double l, 19 | double w, 20 | double b) 21 | { 22 | Length = l; 23 | Width = w; 24 | Breadth = b; 25 | } 26 | 27 | public static Box operator +(Box box1, Box box2) 28 | { 29 | Box newBox = new Box() 30 | { 31 | Length = box1.Length + box2.Length, 32 | Width = box1.Width + box2.Width, 33 | Breadth = box1.Breadth + box2.Breadth 34 | }; 35 | return newBox; 36 | } 37 | 38 | // Through operator overloading you can 39 | // allow users to interact with your 40 | // custom objects in interesting ways 41 | // You can overload +, -, *, /, %, !, 42 | // ==, !=, >, <, >=, <=, ++ and -- 43 | public static Box operator -(Box box1, Box box2) 44 | { 45 | Box newBox = new Box() 46 | { 47 | Length = box1.Length - box2.Length, 48 | Width = box1.Width - box2.Width, 49 | Breadth = box1.Breadth - box2.Breadth 50 | }; 51 | return newBox; 52 | } 53 | 54 | public static bool operator ==(Box box1, Box box2) 55 | { 56 | if ((box1.Length == box2.Length) && 57 | (box1.Width == box2.Width) && 58 | (box1.Breadth == box2.Breadth)) 59 | { 60 | return true; 61 | } 62 | return false; 63 | } 64 | 65 | public static bool operator !=(Box box1, Box box2) 66 | { 67 | if ((box1.Length != box2.Length) || 68 | (box1.Width != box2.Width) || 69 | (box1.Breadth != box2.Breadth)) 70 | { 71 | return true; 72 | } 73 | return false; 74 | } 75 | 76 | // You define how your object is converted 77 | // into a string by overridding ToString 78 | public override string ToString() 79 | { 80 | return String.Format("Box with Height : {0} Width : {1} and Breadth : {2}", 81 | Length, Width, Breadth); 82 | } 83 | 84 | // You can convert from a Box into an 85 | // int like this even though this 86 | // wouldn't make sense 87 | public static explicit operator int(Box b) 88 | { 89 | return (int)(b.Length + b.Width + b.Breadth) / 3; 90 | } 91 | 92 | // Convert from an int to a Box 93 | public static implicit operator Box(int i) 94 | { 95 | // Return a box with the lengths all 96 | // set to the int passed 97 | return new Box(i, i, i); 98 | } 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /C# Code 11/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | using ConsoleApp11; 5 | 6 | /* 7 | We’ll learn about IEnumerable, Indexer, Enumerator, Operator Overloading, Custom 8 | Casting, Anonymous Types and more 9 | */ 10 | 11 | namespace ConsoleApp11 12 | { 13 | // Indexers allow you to access items 14 | // like arrays 15 | 16 | class Program 17 | { 18 | 19 | static void Main(string[] args) 20 | { 21 | // Create an AnimalFarm object 22 | AnimalFarm myAnimals = new AnimalFarm(); 23 | 24 | // Add Animals 25 | myAnimals[0] = new Animal("Wilbur"); 26 | myAnimals[1] = new Animal("Templeton"); 27 | myAnimals[2] = new Animal("Gander"); 28 | myAnimals[3] = new Animal("Charlotte"); 29 | 30 | foreach (Animal i in myAnimals) 31 | { 32 | Console.WriteLine(i.Name); 33 | } 34 | 35 | // Testing operator overloading 36 | Box box1 = new Box(2, 3, 4); 37 | Box box2 = new Box(5, 6, 7); 38 | 39 | Box box3 = box1 + box2; 40 | 41 | // Converts the box to a string with 42 | // ToString 43 | Console.WriteLine($"Box 3 : {box3}"); 44 | 45 | Console.WriteLine($"Box Int : {(int)box3}"); 46 | 47 | // Convert an int into a Box 48 | Box box4 = (Box)4; 49 | 50 | Console.WriteLine($"Box 4 : {(Box)4}"); 51 | 52 | // Sometimes you want to build a simple 53 | // class that contains fields and 54 | // Anonymous types are great for that 55 | var shopkins = new { Name = "Shopkins", Price = 4.99 }; 56 | 57 | Console.WriteLine("{0} cost ${1}", 58 | shopkins.Name, shopkins.Price); 59 | 60 | // Anonymous types can also be stored 61 | // in an array 62 | 63 | var toyArray = new[] { new { 64 | Name = "Yo-Kai Pack", Price = 4.99 }, 65 | new { Name = "Legos", Price = 9.99 } }; 66 | 67 | // You can loop through the array 68 | foreach (var item in toyArray) 69 | { 70 | Console.WriteLine("{0} costs ${1}", 71 | item.Name, item.Price); 72 | } 73 | 74 | Console.WriteLine(); 75 | 76 | Console.ReadLine(); 77 | 78 | } 79 | 80 | } 81 | 82 | } -------------------------------------------------------------------------------- /C# Code 12/Animal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ConsoleApp12 8 | { 9 | class Animal 10 | { 11 | public string Name { get; set; } 12 | public double Weight { get; set; } 13 | public double Height { get; set; } 14 | public int AnimalID { get; set; } 15 | 16 | public Animal(string name = "No Name", 17 | double weight = 0, 18 | double height = 0) 19 | { 20 | Name = name; 21 | Weight = weight; 22 | Height = height; 23 | } 24 | 25 | public override string ToString() 26 | { 27 | return string.Format("{0} weighs {1}lbs and is {2} inches tall", 28 | Name, Weight, Height); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /C# Code 12/Owner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ConsoleApp12 8 | { 9 | class Owner 10 | { 11 | public string Name { get; set; } 12 | public int OwnerID { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /C# Code 12/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections; 4 | using System.Collections.Generic; 5 | using ConsoleApp12; 6 | 7 | namespace CSharpTutA.cs 8 | { 9 | // Language Integrated Query (LINQ) provides 10 | // many tools for working with data 11 | // LINQ is similar to SQL, but it can work 12 | // with data aside from databases 13 | // You manipulate data using Query Expressions 14 | 15 | class Program 16 | { 17 | 18 | static void Main(string[] args) 19 | { 20 | QueryStringArray(); 21 | 22 | // Get the array returned and print it 23 | int[] intArray = QueryIntArray(); 24 | 25 | foreach (int i in intArray) 26 | Console.WriteLine(i); 27 | 28 | Console.WriteLine(); 29 | 30 | QueryArrayList(); 31 | 32 | QueryCollection(); 33 | 34 | QueryAnimalData(); 35 | 36 | Console.ReadLine(); 37 | 38 | } 39 | 40 | static void QueryStringArray() 41 | { 42 | string[] dogs = {"K 9", "Brian Griffin", 43 | "Scooby Doo", "Old Yeller", "Rin Tin Tin", 44 | "Benji", "Charlie B. Barkin", "Lassie", 45 | "Snoopy"}; 46 | 47 | // Get strings with spaces and put in 48 | // alphabetical order 49 | 50 | // from states where data comes from and 51 | // where to store each piece as you cycle 52 | 53 | // where defines conditions that must be met 54 | 55 | // orderby defines what data is used for 56 | // ordering results (ascending / descending) 57 | 58 | // select defines the variable that is 59 | // checked against the condition 60 | var dogSpaces = from dog in dogs 61 | where dog.Contains(" ") 62 | orderby dog descending 63 | select dog; 64 | 65 | foreach (var i in dogSpaces) 66 | { 67 | Console.WriteLine(i); 68 | } 69 | 70 | Console.WriteLine(); 71 | 72 | } 73 | 74 | static int[] QueryIntArray() 75 | { 76 | int[] nums = { 5, 10, 15, 20, 25, 30, 35 }; 77 | 78 | // Get numbers bigger then 20 79 | var gt20 = from num in nums 80 | where num > 20 81 | orderby num 82 | select num; 83 | 84 | foreach (var i in gt20) 85 | { 86 | Console.WriteLine(i); 87 | } 88 | 89 | Console.WriteLine(); 90 | 91 | // The type is an enumerable 92 | Console.WriteLine($"Get Type : {gt20.GetType()}"); 93 | 94 | // You can convert it into a List or array 95 | var listGT20 = gt20.ToList(); 96 | var arrayGT20 = gt20.ToArray(); 97 | 98 | // If you change the data the query 99 | // automatically updates 100 | nums[0] = 40; 101 | 102 | foreach (var i in gt20) 103 | { 104 | Console.WriteLine(i); 105 | } 106 | 107 | Console.WriteLine(); 108 | 109 | return arrayGT20; 110 | 111 | } 112 | 113 | static void QueryArrayList() 114 | { 115 | ArrayList famAnimals = new ArrayList() 116 | { 117 | new Animal{Name = "Heidi", 118 | Height = .8, 119 | Weight = 18}, 120 | 121 | new Animal 122 | { 123 | Name = "Shrek", 124 | Height = 4, 125 | Weight = 130 126 | }, 127 | 128 | new Animal 129 | { 130 | Name = "Congo", 131 | Height = 3.8, 132 | Weight = 90 133 | } 134 | }; 135 | 136 | // You have to convert the ArrayList into 137 | // an IEnumerable 138 | var famAnimalEnum = famAnimals.OfType(); 139 | 140 | var smAnimals = from animal in famAnimalEnum 141 | where animal.Weight <= 90 142 | orderby animal.Name 143 | select animal; 144 | 145 | foreach (var animal in smAnimals) 146 | { 147 | Console.WriteLine("{0} weighs {1}lbs", 148 | animal.Name, animal.Weight); 149 | } 150 | 151 | Console.WriteLine(); 152 | 153 | } 154 | 155 | static void QueryCollection() 156 | { 157 | var animalList = new List() 158 | { 159 | new Animal{Name = "German Shepherd", 160 | Height = 25, 161 | Weight = 77}, 162 | new Animal{Name = "Chihuahua", 163 | Height = 7, 164 | Weight = 4.4}, 165 | new Animal{Name = "Saint Bernard", 166 | Height = 30, 167 | Weight = 200} 168 | }; 169 | 170 | var animalListEnum = animalList.OfType(); 171 | 172 | var bigDogs = from dog in animalListEnum 173 | where (dog.Weight > 70) && (dog.Height > 25) 174 | orderby dog.Name 175 | select dog; 176 | 177 | foreach (var dog in bigDogs) 178 | { 179 | Console.WriteLine("A {0} weighs {1}lbs", 180 | dog.Name, dog.Weight); 181 | } 182 | 183 | Console.WriteLine(); 184 | 185 | } 186 | 187 | static void QueryAnimalData() 188 | { 189 | Animal[] animals = new[] 190 | { 191 | new Animal{Name = "German Shepherd", 192 | Height = 25, 193 | Weight = 77, 194 | AnimalID = 1}, 195 | new Animal{Name = "Chihuahua", 196 | Height = 7, 197 | Weight = 4.4, 198 | AnimalID = 2}, 199 | new Animal{Name = "Saint Bernard", 200 | Height = 30, 201 | Weight = 200, 202 | AnimalID = 3}, 203 | new Animal{Name = "Pug", 204 | Height = 12, 205 | Weight = 16, 206 | AnimalID = 1}, 207 | new Animal{Name = "Beagle", 208 | Height = 15, 209 | Weight = 23, 210 | AnimalID = 2} 211 | }; 212 | 213 | Owner[] owners = new[] 214 | { 215 | new Owner{Name = "Doug Parks", 216 | OwnerID = 1}, 217 | new Owner{Name = "Sally Smith", 218 | OwnerID = 2}, 219 | new Owner{Name = "Paul Brooks", 220 | OwnerID = 3} 221 | }; 222 | 223 | // Remove name and height 224 | var nameHeight = from a in animals 225 | select new 226 | { 227 | a.Name, 228 | a.Height 229 | }; 230 | 231 | // Convert to an object array 232 | Array arrNameHeight = nameHeight.ToArray(); 233 | 234 | foreach (var i in arrNameHeight) 235 | { 236 | Console.WriteLine(i.ToString()); 237 | } 238 | Console.WriteLine(); 239 | 240 | // Create an inner join 241 | // Join info in owners and animals using 242 | // equal values for IDs 243 | // Store values for animal and owner 244 | var innerJoin = 245 | from animal in animals 246 | join owner in owners on animal.AnimalID 247 | equals owner.OwnerID 248 | select new { OwnerName = owner.Name, AnimalName = animal.Name }; 249 | 250 | foreach (var i in innerJoin) 251 | { 252 | Console.WriteLine("{0} owns {1}", 253 | i.OwnerName, i.AnimalName); 254 | } 255 | 256 | Console.WriteLine(); 257 | 258 | // Create a group inner join 259 | // Get all animals and put them in a 260 | // newly created owner group if their 261 | // IDs match the owners ID 262 | var groupJoin = 263 | from owner in owners 264 | orderby owner.OwnerID 265 | join animal in animals on owner.OwnerID 266 | equals animal.AnimalID into ownerGroup 267 | select new 268 | { 269 | Owner = owner.Name, 270 | Animals = from owner2 in ownerGroup 271 | orderby owner2.Name 272 | select owner2 273 | }; 274 | 275 | int totalAnimals = 0; 276 | 277 | foreach (var ownerGroup in groupJoin) 278 | { 279 | Console.WriteLine(ownerGroup.Owner); 280 | foreach (var animal in ownerGroup.Animals) 281 | { 282 | totalAnimals++; 283 | Console.WriteLine("* {0}", animal.Name); 284 | } 285 | } 286 | } 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /C# Code 13/BankAcct.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ConsoleApp13 8 | { 9 | class BankAcct 10 | { 11 | private Object acctLock = new Object(); 12 | double Balance { get; set; } 13 | string Name { get; set; } 14 | 15 | public BankAcct(double bal) 16 | { 17 | Balance = bal; 18 | } 19 | 20 | public double Withdraw(double amt) 21 | { 22 | if ((Balance - amt) < 0) 23 | { 24 | Console.WriteLine($"Sorry ${Balance} in Account"); 25 | return Balance; 26 | } 27 | 28 | lock (acctLock) 29 | { 30 | if (Balance >= amt) 31 | { 32 | Console.WriteLine("Removed {0} and {1} left in Account", 33 | amt, (Balance - amt)); 34 | Balance -= amt; 35 | } 36 | 37 | return Balance; 38 | 39 | } 40 | } 41 | 42 | // You can only point at methods 43 | // without arguments and that return 44 | // nothing 45 | public void IssueWithdraw() 46 | { 47 | Withdraw(1); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /C# Code 13/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections; 4 | using System.Collections.Generic; 5 | using System.Threading; 6 | 7 | namespace CSharpTutA.cs 8 | { 9 | // With threads you can execute multiple 10 | // pieces of code that share resources 11 | // and data without corrupting it 12 | 13 | // You can't guarantee when a thread 14 | // executes. You also must lock resources 15 | // until a thread is done with them 16 | // or you could corrupt them 17 | 18 | class Program 19 | { 20 | // ----- Simple Thread Example ----- 21 | 22 | static void Main(string[] args) 23 | { 24 | // We will randomly print 1 or 0 25 | // Create a thread and start it 26 | Thread t = new Thread(Print1); 27 | t.Start(); 28 | 29 | // This code will run randomly 30 | for (int i = 0; i < 1000; i++) 31 | Console.Write(0); 32 | 33 | Console.ReadLine(); 34 | 35 | } 36 | 37 | static void Print1() 38 | { 39 | for (int i = 0; i < 1000; i++) 40 | Console.Write(1); 41 | } 42 | } 43 | 44 | /* 45 | // ----- Sleep Example ----- 46 | 47 | // With sleep() the thread is suspended 48 | // for the designated amount of time 49 | static void Main(string[] args) 50 | { 51 | int num = 1; 52 | for (int i = 0; i < 10; i++) 53 | { 54 | Console.WriteLine(num); 55 | 56 | // Pause for 1 second 57 | Thread.Sleep(1000); 58 | 59 | num++; 60 | } 61 | 62 | Console.WriteLine("Thread Ends"); 63 | 64 | Console.ReadLine(); 65 | } 66 | 67 | // ----- Lock Example ----- 68 | // lock keeps other threads from entering 69 | // a statement block until another thread 70 | // leaves 71 | static void Main(string[] args) 72 | { 73 | BankAcct acct = new BankAcct(10); 74 | Thread[] threads = new Thread[15]; 75 | 76 | // CurrentThread gets you the current 77 | // executing thread 78 | Thread.CurrentThread.Name = "main"; 79 | 80 | // Create 15 threads that will call for 81 | // IssueWithdraw to execute 82 | for (int i = 0; i < 15; i++) 83 | { 84 | // You can only point at methods 85 | // without arguments and that return 86 | // nothing 87 | Thread t = new Thread(new 88 | ThreadStart(acct.IssueWithdraw)); 89 | t.Name = i.ToString(); 90 | threads[i] = t; 91 | } 92 | 93 | // Have threads try to execute 94 | for (int i = 0; i < 15; i++) 95 | { 96 | // Check if thread has started 97 | Console.WriteLine("Thread {0} Alive : {1}", 98 | threads[i].Name, threads[i].IsAlive); 99 | 100 | // Start thread 101 | threads[i].Start(); 102 | 103 | // Check if thread has started 104 | Console.WriteLine("Thread {0} Alive : {1}", 105 | threads[i].Name, threads[i].IsAlive); 106 | } 107 | 108 | // Get thread priority (Normal Default) 109 | // Also Lowest, BelowNormal, AboveNormal 110 | // and Highest 111 | // Changin priority doesn't guarantee 112 | // the highest precedence though 113 | // It is best to not mess with this 114 | Console.WriteLine("Current Priority : {0}", 115 | Thread.CurrentThread.Priority); 116 | 117 | Console.WriteLine("Thread {0} Ending", 118 | Thread.CurrentThread.Name); 119 | 120 | Console.ReadLine(); 121 | } 122 | } 123 | 124 | // ----- Passing Data to Threads ----- 125 | // You can pass arguments to a thread 126 | // using a lambda expression 127 | 128 | static void Main(string[] args) 129 | { 130 | Thread t = new Thread(() => CountTo(10)); 131 | t.Start(); 132 | 133 | // You can use multiline lambdas 134 | new Thread(() => 135 | { 136 | CountTo(5); 137 | CountTo(6); 138 | }).Start(); 139 | 140 | Console.ReadLine(); 141 | } 142 | 143 | static void CountTo(int maxNum) 144 | { 145 | for(int i = 0; i <= maxNum; i++) 146 | { 147 | Console.WriteLine(i); 148 | } 149 | } 150 | 151 | } 152 | 153 | */ 154 | } -------------------------------------------------------------------------------- /C# Code 14/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections; 4 | using System.Collections.Generic; 5 | 6 | // Used for file and directory 7 | // manipulation 8 | using System.IO; 9 | using System.Text; 10 | 11 | // Start VS with admin rights by 12 | // right clicking it and run as 13 | // administrator 14 | 15 | namespace ConsoleApp14 16 | { 17 | 18 | class Program 19 | { 20 | 21 | static void Main(string[] args) 22 | { 23 | // ----- MESSING WITH DIRECTORIES ----- 24 | 25 | // Get access to the current directory 26 | DirectoryInfo currDir = new DirectoryInfo("."); 27 | 28 | // Get access to a directory with a path 29 | DirectoryInfo dereksDir = new DirectoryInfo(@"C:\Users\derek"); 30 | 31 | // Get the directory path 32 | Console.WriteLine(dereksDir.FullName); 33 | 34 | // Get the directory name 35 | Console.WriteLine(dereksDir.Name); 36 | 37 | // Get the parent directory 38 | Console.WriteLine(dereksDir.Parent); 39 | 40 | // What type is it 41 | Console.WriteLine(dereksDir.Attributes); 42 | 43 | // When was it created 44 | Console.WriteLine(dereksDir.CreationTime); 45 | 46 | // Create a directory 47 | DirectoryInfo dataDir = new DirectoryInfo(@"C:\Users\derek\C#Data"); 48 | dataDir.Create(); 49 | 50 | // Delete a directory 51 | // Directory.Delete(@"C:\Users\derekbanas\C#Data"); 52 | 53 | // ----- SIMPLE FILE READING & WRITING ----- 54 | 55 | // Write a string array to a text file 56 | string[] customers = 57 | { 58 | "Bob Smith", 59 | "Sally Smith", 60 | "Robert Smith" 61 | }; 62 | 63 | string textFilePath = @"C:\Users\derek\C#Data\testfile1.txt"; 64 | ; 65 | // Write the array 66 | File.WriteAllLines(textFilePath, 67 | customers); 68 | 69 | // Read strings from array 70 | foreach (string cust in File.ReadAllLines(textFilePath)) 71 | { 72 | Console.WriteLine($"Customer : {cust}"); 73 | } 74 | 75 | // ----- GETTING FILE DATA ----- 76 | 77 | DirectoryInfo myDataDir = new DirectoryInfo(@"C:\Users\derek\C#Data"); 78 | 79 | // Get all txt files 80 | FileInfo[] txtFiles = myDataDir.GetFiles("*.txt", 81 | SearchOption.AllDirectories); 82 | 83 | // Number of matches 84 | Console.WriteLine("Matches : {0}", 85 | txtFiles.Length); 86 | 87 | foreach (FileInfo file in txtFiles) 88 | { 89 | // Get file name 90 | Console.WriteLine(file.Name); 91 | 92 | // Get bytes in file 93 | Console.WriteLine(file.Length); 94 | } 95 | 96 | // ----- FILESTREAMS ----- 97 | // FileStream is used to read and write a byte 98 | // or an array of bytes. 99 | 100 | string textFilePath2 = @"C:\Users\derek\C#Data\testfile2.txt"; 101 | 102 | // Create and open a file 103 | FileStream fs = File.Open(textFilePath2, 104 | FileMode.Create); 105 | 106 | string randString = "This is a random string"; 107 | 108 | // Convert to a byte array 109 | byte[] rsByteArray = Encoding.Default.GetBytes(randString); 110 | 111 | // Write to file by defining the byte array, 112 | // the index to start writing from and length 113 | fs.Write(rsByteArray, 0, 114 | rsByteArray.Length); 115 | 116 | // Move back to the beginning of the file 117 | fs.Position = 0; 118 | 119 | // Create byte array to hold file data 120 | byte[] fileByteArray = new byte[rsByteArray.Length]; 121 | 122 | // Put bytes in array 123 | for (int i = 0; i < rsByteArray.Length; i++) 124 | { 125 | fileByteArray[i] = (byte)fs.ReadByte(); 126 | } 127 | 128 | // Convert from bytes to string and output 129 | Console.WriteLine(Encoding.Default.GetString(fileByteArray)); 130 | 131 | // Close the FileStream 132 | fs.Close(); 133 | 134 | // ----- STREAMWRITER / STREAMREADER ----- 135 | // These are best for reading and writing strings 136 | 137 | string textFilePath3 = @"C:\Users\derek\C#Data\testfile3.txt"; 138 | 139 | // Create a text file 140 | StreamWriter sw = File.CreateText(textFilePath3); 141 | 142 | // Write to a file without a newline 143 | sw.Write("This is a random "); 144 | 145 | // Write to a file with a newline 146 | sw.WriteLine("sentence."); 147 | 148 | // Write another 149 | sw.WriteLine("This is another sentence."); 150 | 151 | // Close the StreamWriter 152 | sw.Close(); 153 | 154 | // Open the file for reading 155 | StreamReader sr = File.OpenText(textFilePath3); 156 | 157 | // Peek returns the next character as a unicode 158 | // number. Use Convert to change to a character 159 | Console.WriteLine("Peek : {0}", 160 | Convert.ToChar(sr.Peek())); 161 | 162 | // Read to a newline 163 | Console.WriteLine("1st String : {0}", 164 | sr.ReadLine()); 165 | 166 | // Read to the end of the file starting 167 | // where you left off reading 168 | Console.WriteLine("Everything : {0}", 169 | sr.ReadToEnd()); 170 | 171 | sr.Close(); 172 | 173 | // ----- BINARYWRITER / BINARYREADER ----- 174 | // Used to read and write data types 175 | string textFilePath4 = @"C:\Users\derek\C#Data\testfile4.dat"; 176 | 177 | // Get the file 178 | FileInfo datFile = new FileInfo(textFilePath4); 179 | 180 | // Open the file 181 | BinaryWriter bw = new BinaryWriter(datFile.OpenWrite()); 182 | 183 | // Data to save to the file 184 | string randText = "Random Text"; 185 | int myAge = 42; 186 | double height = 6.25; 187 | 188 | // Write data to a file 189 | bw.Write(randText); 190 | bw.Write(myAge); 191 | bw.Write(height); 192 | 193 | bw.Close(); 194 | 195 | // Open file for reading 196 | BinaryReader br = new BinaryReader(datFile.OpenRead()); 197 | 198 | // Output data 199 | Console.WriteLine(br.ReadString()); 200 | Console.WriteLine(br.ReadInt32()); 201 | Console.WriteLine(br.ReadDouble()); 202 | 203 | br.Close(); 204 | 205 | } 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /C# Code 15/Animal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.Serialization; 3 | using System.Runtime.Serialization.Formatters.Binary; 4 | 5 | // With serialization you can store the state 6 | // of an object in a file stream, pass it to 7 | // a remote network 8 | 9 | namespace ConsoleApp15 10 | { 11 | // Defines that you want to serialize this class 12 | [Serializable()] 13 | public class Animal : ISerializable 14 | { 15 | public string Name { get; set; } 16 | public double Weight { get; set; } 17 | public double Height { get; set; } 18 | public int AnimalID { get; set; } 19 | 20 | public Animal() { } 21 | 22 | public Animal(string name = "No Name", 23 | double weight = 0, 24 | double height = 0) 25 | { 26 | Name = name; 27 | Weight = weight; 28 | Height = height; 29 | } 30 | 31 | public override string ToString() 32 | { 33 | return string.Format("{0} weighs {1} lbs and is {2} inches tall", 34 | Name, Weight, Height); 35 | } 36 | 37 | // Serialization function (Stores Object Data in File) 38 | // SerializationInfo holds the key value pairs 39 | // StreamingContext can hold additional info 40 | // but we aren't using it here 41 | public void GetObjectData(SerializationInfo info, StreamingContext context) 42 | { 43 | // Assign key value pair for your data 44 | info.AddValue("Name", Name); 45 | info.AddValue("Weight", Weight); 46 | info.AddValue("Height", Height); 47 | info.AddValue("AnimalID", AnimalID); 48 | } 49 | 50 | // The deserialize function (Removes Object Data from File) 51 | public Animal(SerializationInfo info, StreamingContext ctxt) 52 | { 53 | //Get the values from info and assign them to the properties 54 | Name = (string)info.GetValue("Name", typeof(string)); 55 | Weight = (double)info.GetValue("Weight", typeof(double)); 56 | Height = (double)info.GetValue("Height", typeof(double)); 57 | AnimalID = (int)info.GetValue("AnimalID", typeof(int)); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /C# Code 15/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections; 4 | using System.Collections.Generic; 5 | 6 | // Used for writing to a file 7 | using System.IO; 8 | 9 | // Used to serialize an object to binary format 10 | using System.Runtime.Serialization.Formatters.Binary; 11 | 12 | // Used to serialize into XML 13 | using System.Xml.Serialization; 14 | using ConsoleApp15; 15 | 16 | namespace ConsoleApp15 17 | { 18 | class Program 19 | { 20 | 21 | static void Main(string[] args) 22 | { 23 | Animal bowser = new Animal("Bowser", 45, 25); 24 | 25 | // Serialize the object data to a file 26 | Stream stream = File.Open("AnimalData.dat", FileMode.Create); 27 | BinaryFormatter bf = new BinaryFormatter(); 28 | 29 | // Send the object data to the file 30 | bf.Serialize(stream, bowser); 31 | stream.Close(); 32 | 33 | // Delete the bowser data 34 | bowser = null; 35 | 36 | // Read object data from the file 37 | stream = File.Open("AnimalData.dat", FileMode.Open); 38 | bf = new BinaryFormatter(); 39 | 40 | bowser = (Animal)bf.Deserialize(stream); 41 | stream.Close(); 42 | 43 | Console.WriteLine(bowser.ToString()); 44 | 45 | // Change bowser to show changes were made 46 | bowser.Weight = 50; 47 | 48 | // XmlSerializer writes object data as XML 49 | // Make sure you have a C#Data folder 50 | XmlSerializer serializer = new XmlSerializer(typeof(Animal)); 51 | using (TextWriter tw = new StreamWriter(@"C:\Users\derek\C#Data\bowser.xml")) 52 | { 53 | serializer.Serialize(tw, bowser); 54 | } 55 | 56 | // Delete bowser data 57 | bowser = null; 58 | 59 | // Deserialize from XML to the object 60 | XmlSerializer deserializer = new XmlSerializer(typeof(Animal)); 61 | TextReader reader = new StreamReader(@"C:\Users\derek\C#Data\bowser.xml"); 62 | object obj = deserializer.Deserialize(reader); 63 | bowser = (Animal)obj; 64 | reader.Close(); 65 | 66 | Console.WriteLine(bowser.ToString()); 67 | 68 | // Save a collection of Animals 69 | List theAnimals = new List 70 | { 71 | new Animal("Mario", 60, 30), 72 | new Animal("Luigi", 55, 24), 73 | new Animal("Peach", 40, 20) 74 | }; 75 | 76 | using (Stream fs = new FileStream(@"C:\Users\derek\C#Data\animals.xml", 77 | FileMode.Create, FileAccess.Write, FileShare.None)) 78 | { 79 | XmlSerializer serializer2 = new XmlSerializer(typeof(List)); 80 | serializer2.Serialize(fs, theAnimals); 81 | } 82 | 83 | // Delete list data 84 | theAnimals = null; 85 | 86 | // Read data from XML 87 | XmlSerializer serializer3 = new XmlSerializer(typeof(List)); 88 | 89 | using (FileStream fs2 = File.OpenRead(@"C:\Users\derek\C#Data\animals.xml")) 90 | { 91 | theAnimals = (List)serializer3.Deserialize(fs2); 92 | } 93 | 94 | 95 | foreach (Animal a in theAnimals) 96 | { 97 | Console.WriteLine(a.ToString()); 98 | } 99 | 100 | Console.ReadLine(); 101 | 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /C# Code 16/Program.cs: -------------------------------------------------------------------------------- 1 | // Right click table and add a new table 2 | // A key is automatically added but we want it to be the 3 | // primary key 4 | // Select it and then under properties change Is Identity 5 | // under Identity Specification to True 6 | 7 | // Change table name to Store 8 | // Add Name as nvarchar(100) <- Variable length 9 | // Add Street as nvarchar(100) 10 | // Add City as nvarchar(50) 11 | // Add State as nchar(2) <- Max length 2 characters 12 | // Add Zip as int 13 | // Click Update and Refresh 14 | 15 | // Right Click Store in Server Explorer 16 | // Click Show Table Data 17 | // 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /C# Code 17/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  9 | 10 |