Concepts for C#
C# is a modern, object-oriented programming language developed by Microsoft as part of its .NET framework. It combines the power and flexibility of C++ with the simplicity of Visual Basic. C# is designed for building robust, scalable applications across various platforms, including desktop, web, and mobile. It features strong typing, automatic memory management through garbage collection, and a rich standard library. With features like LINQ (Language-Integrated Query) and async/await for asynchronous programming, C# enables developers to write clean, efficient code with high productivity. Additionally, C# is closely integrated with Microsoft technologies, making it a popular choice for Windows application development.
Print Text
public class HelloWorld { public static void Main(String[] args) { Console.WriteLine("Hello World!"); } }
Comments
// one line comment /* multi line comment */
Variables
int carCount = 2; string name = "Joe"; bool isPurple = true;
Data Types
int carCount = 2; uint age = 15; short seaLevel = -10000; long usBudget = 11000000000; ulong lightSpeed = 11799312874; float myGPA = 3.45F; double piValue = 3.14159265D; char lastLetter = 'Z'; bool isMale = true; string myName = "Joe";
Math Op
int carCount = 6; int truckCount = 3; int total = carCount + truckCount; Console.WriteLine(total + "\n"); int subtract = carCount - truckCount; Console.WriteLine(subtract + "\n"); int multiple = carCount * truckCount; Console.WriteLine(multiple + "\n"); int divisible = carCount / truckCount; Console.WriteLine(divisible + "\n"); // performs division and gets remainder which is 0 int modulo = carCount % truckCount; Console.WriteLine(modulo + "\n");
Math Functions
double power = Math.pow(3.0, 6.0); Console.WriteLine(power); double root = Math.Sqrt(16.0); Console.WriteLine(root); double floorVal = Math.Floor(3.14); Console.WriteLine(floorVal); double ceilVal = Math.Ceiling(4.3); Console.WriteLine(ceilVal); double roundVal = Math.Round(3.4); Console.WriteLine(roundVal); // random number from 0 to 100 Random rand = new Random(); int ranNum = rand.Next(0, 101); Console.WriteLine(ranNum);
If/Else
int carCount = 6; if (carCount > 3) { Console.WriteLine("More than three cars"); } else if (carCount == 3) { Console.WriteLine("Equal to three cars"); } else { Console.WriteLine("Less than three cars"); }
Ternary
int carCount = 3; string result = (carCount > 2) ? "Yes" : "No"; Console.WriteLine(result);
Switch
int carCount = 3; switch (carCount) { case 1: Console.WriteLine("One car"); break; case 2: Console.WriteLine("Two cars"); break; case 3: Console.WriteLine("Three cars"); break; default: Console.WriteLine("More than three"); break; }
Functions
static int handleCars(int cars, int wheels) { int total = cars * wheels; return total; } int result = handleCars(3, 4); Console.WriteLine(result);
Interpolation
string name = "Joe"; string car = "Mazda"; string result = format("{} drives a {}", name, car); Console.WriteLine(result);
Type Casting
String squareA(int length) { double result = (double)(Math.Pow(length, 2)); return result.ToString(); } String squareL = "4"; int convertedVal = int.Parse(squareL); String area = squareA(convertedVal); Console.WriteLine(area);
Date and Time
// get current date DateTime now = DateTime.Now; Console.WriteLine(now); // find tim in milliseconds long millitime = (long)( now - new DateTime(1970, 1, 1) ).TotalMilliseconds; Console.WriteLine(millitime); // create date time obj DateTime date = new DateTime(2023, 11, 20); Console.WriteLine(date.ToString()); // finds the current year String currentYear = DateTime.Now.Year.ToString(); Console.WriteLine(currentYear); // finds current date and formats it String currentDate = DateTime.Now.ToString("MM/dd/yyyy"); Console.WriteLine(currentDate);
Classes
using System; using System.Collections.Generic; public class Cars { protected List<string> carList = new List<string>(); public void addCar(string car) { carList.Add(car); } public void removeFirst() { carList.RemoveAt(0); } public string getFirstVal() { if (carList.Count > 0) { return carList[0]; } return ""; } public static void Main(string[] args) { Cars newList = new Cars(); newList.addCar("Honda"); newList.addCar("Mazda"); newList.addCar("Toyota"); newList.removeFirst(); string firstCar = newList.getFirstVal(); Console.WriteLine(firstCar); } }
Inheritance
class User { protected string username; protected string password; public User( string Username, string Password ) { username = Username; password = Password; } } class Admin: User { protected string id; public Admin( string username, string password, string Id ): base(username, password) { id = Id; } public string getUsername() { return username; } public string getAdminID() { return id; } } public class Test { public static void Main(string[] args) { Admin newAdmin = new Admin( "alpha0", "pw1", "1FE" ); Console.WriteLine( newAdmin.getUsername() ); Console.WriteLine( newAdmin.getAdminID() ); } }
Method Overload
class UserForm { public string formA = "alpha"; public string formB = "beta"; public string formC = "gamma"; public string formD = "epsilon"; public string getForm(int age) { if (age > 65) { return formA; } return formB; } public string getForm(string id) { if (id == "1FE") { return formA; } return formC; } public string getForm( bool isMilitary, bool isNasa ) { if (isMilitary || isNasa) { return formD; } return formA; } } UserForm form = new UserForm(); int myAge = 67; string myId = "1FE"; bool veteran = false; bool nasa = true; string form1 = form.getForm(myAge); string form2 = form.getForm(myId); string form3 = form.getForm(veteran, nasa); Console.WriteLine(form1 + "\n"); Console.WriteLine(form2 + "\n"); Console.WriteLine(form3 + "\n");
Abstract Class
abstract class Animation { public abstract void walk(); public abstract void run(); public abstract void idle(); } class Human: Animation { public override void walk() { Console.WriteLine("Human walks" ); } public override void run() { Console.WriteLine("Human runs" ); } public override void idle() { Console.WriteLine("Human idles" ); } } class Zombie: Animation { public override void walk() { Console.WriteLine("Zombie walks" ); } public override void run() { Console.WriteLine("Zombie runs" ); } public override void idle() { Console.WriteLine("Zombie idles" ); } } Human player = new Human(); player.walk(); Zombie boss1 = new Zombie(); boss1.run();
Static Class
public static class Helper { public static double CircleA(int radius) { double power = Math.pow(radius, 2); return (double)(3.14 * power); } public static double SquareA(int length) { return (double)(Math.pow(length, 2)); } }; double circle = Helper.CircleA(3); Console.WriteLine(circle); double square = Helper.SquareA(4); Console.WriteLine(square);
Arrays/Lists
string[] names = new string[] {"Joe", "Alex", "Box"}; names[1] = "Tom"; string name = names[1]; int numItems = names.Length; Console.WriteLine(name); Console.WriteLine(numItems);
Array Methods
List<string> cars = new List<string>(); cars.Add("Honda"); cars.Add("Mazda"); cars.Add("Toyota"); // check existence of key Mazda Console.WriteLine(cars.Contains("Mazda")); // removes item at index 1 Console.WriteLine(cars[1] ); cars.RemoveAt(1); Console.WriteLine(cars[1] ); // removes elements with matching balue cars.Remove("Honda"); Console.WriteLine(cars[0]); // count number of elements Console.WriteLine(cars.Count);
Concatenation
List<string> carsListKr = new List <string>(); carsListKr.Add("Kia"); carsListKr.Add("Hyundai"); carsListKr.Add("Daewoo"); List<string> carsListJp = new List <string>(); carsListJp.Add("Honda"); carsListJp.Add("Mazda"); carsListJp.Add("Toyota"); List<string> combined = new List<string>(); combined.AddRange(carsListKr); combined.AddRange(carsListJp); Console.WriteLine(combined[1]); Console.WriteLine(combined[4]);
Sort Method
using System.Collections.Generic; List<int> ages = new List<int>(); ages.Add(5); ages.Add(3); ages.Add(1); ages.Add(6); ages.Add(7); ages.Add(4); ages.Add(19); ages.Sort(); for (int i = 0; i < ages.Count; i++) { Console.WriteLine(ages[i] + "\n"); }
Objects
public class User { public string first; public string last; public int age; public bool retired; public string[] carBrands; public User ( string First, string Last, int Age, bool Retired, string[] CarBrands ) { first = First; last = Last; retired = Retired; carBrands = CarBrands; } public string fullName() { return $"{first} {last}"; } public static void Main(string[] args) { string[] brands = {"Mazda", "Toyota"}; User user = new User ( "Joe", "Doe", 23, false, brands ); Console.WriteLine(user.first); Console.WriteLine(user.carBrands[1]); Console.WriteLine(user.fullName()); } }
Maps (Key/Value)
using System.Collections.Generic; Dictionary<string, string> carMap = new Dictionary<string, string>(); carMap.Add("Joe", "Toyota"); carMap.Add("Bob", "Mazda"); carMap.Add("Tom", "Ford"); try { Console.WriteLine(carMap["Tom"]); carMap.Remove("Tom"); Console.WriteLine(carMap["Tom"]); } catch{ Console.WriteLine("Key not found!"); }
Sets
using System.Collections.Generic; HashSet<string> cars = new HashSet<string>(); cars.Add("Mazda"); cars.Add("Toyota"); cars.Add("Honda"); Console.WriteLine(cars.Contains("Honda") + "\n"); cars.Remove("Honda"); Console.WriteLine(cars.Contains("Honda"));
Stack
using System.Collections.Generic; Stack<string> cars = new Stack<string>(); cars.Push("Mazda"); cars.Push("Toyota"); cars.Push("Honda"); Console.WriteLine( cars.Contains("Honda") + "\n" ); cars.Pop(); Console.WriteLine( cars.Contains("Honda") );
Queues
using System.Collections.Generic; Queue<string> cars = new Queue<string>(); cars.Enqueue("Mazda"); cars.Enqueue("Toyota"); cars.Enqueue("Honda"); Console.WriteLine( cars.Contains("Mazda") + "\n" ); cars.Dequeue(); Console.WriteLine( cars.Contains("Mazda") );
Linked List
using System; using System.Collections.Generic; public class Node { public string value; public Node next; public Node(string Value) { value = Value; } } public class LinkedList { public Node head = null; public void addValue(string val) { Node newNode = new Node(val); if (head == null) { head = newNode; } else { Node current = head; while(current.next != null) { current = current.next; } current.next = newNode; } } public string returnHead() { return head.value; } public void traverse() { Node current = head; while(current != null) { Console.WriteLine(current.value ); current = current.next; } } public static void Main(string[] args) { LinkedList carList = new LinkedList(); carList.addValue("Mazda"); carList.addValue("Toyota"); carList.addValue("Honda"); Console.WriteLine(carList.returnHead()); carList.traverse(); } }
Graphs
using System; using System.Collections.Generic; public class Graph { Dictionary<string, List<string>> graphMap = new Dictionary<string, List<string>>(); public void addNode(string val) { List<string> tempList = new List<string>(); graphMap.Add(val, tempList); } public void addVertices( string node1, string node2 ) { List<string> tempArr = new List<string>(); if(graphMap.ContainsKey(node1) == false) { graphMap.Add(node1, tempArr); } if(graphMap.ContainsKey(node2) == false) { graphMap.Add(node2, tempArr); } graphMap[node1].Add(node2); graphMap[node2].Add(node1); } public void breadthTraverse(string start) { Queue<string> queue = new Queue<string>(); queue.Enqueue(start); Dictionary<string, bool> visited = new Dictionary<string, bool>(); visited.Add(start, true); while(queue.Count > 0) { string val = queue.Dequeue(); Console.WriteLine(val + "\n"); List<string> tempArr = graphMap[val]; for (int i = 0; i < tempArr.Count; i++) { string tempKey = tempArr[i]; if( visited.ContainsKey(tempKey) == false ) { queue.Enqueue(tempKey); visited.Add(tempKey, true); } } } } public void depthTraverse(string start) { Stack<string> stack = new Stack<string>(); stack.Push(start); Dictionary<string, bool> visited = new Dictionary<string, bool>(); visited.Add(start, true); while(stack.Count > 0) { string val = stack.Pop(); Console.WriteLine(val + "\n"); List<string> tempArr = graphMap[val]; for (int i = 0; i < tempArr.Count; i++) { string tempKey = tempArr[i]; if( visited.ContainsKey(tempKey) == false ) { stack.Push(tempKey); visited.Add(tempKey, true); } } } } public static void Main(string[] args) { Graph newGraph = new Graph(); newGraph.addNode("a"); newGraph.addVertices("a", "b"); newGraph.addVertices("a", "c"); newGraph.addVertices("b", "d"); newGraph.addVertices("b", "e"); newGraph.addVertices("d", "f"); newGraph.addVertices("d", "g"); newGraph.addVertices("d", "h"); newGraph.addVertices("e", "i"); newGraph.addVertices("e", "j"); newGraph.breadthTraverse("a"); newGraph.depthTraverse("a"); } }
For Loops
using System.Collections.Generic; List<string> names = new List<string>(); names.Add("Joe"); names.Add("Alex"); names.Add("Bob"); for (int i = 0; i < names.Count; i++) { Console.WriteLine(names[i]); }
While Loops
using System.Collections.Generic; List<string> carList = new List<string>(); carList.Add("Mazda"); carList.Add("Toyota"); carList.Add("Honda"); while(carList.Count > 0) { Console.WriteLine(carList[0] + "\n"); carList.RemoveAt(0); } Console.WriteLine(carList.Count);
Loop Breaks
using System.Collections.Generic; List<string> cars = new List<string>(); cars.Add("Toyota"); cars.Add("Honda"); cars.Add("Mazda"); for (int i = 0; i < cars.Count; i++) { if (cars[i] == "Honda") { Console.WriteLine("Found at index " + i + "\n"); break; } Console.WriteLine("Visited index " + i + "\n"); }
Recursion
using System.Collections.Generic; int getSum(List<int> arr) { if (arr.Count == 0) return 0; int firstVal = arr[0]; arr.RemoveAt(0); Console.WriteLine(firstVal +"\n"); return firstVal + getSum(arr); } List<int> testArr = new List<int>(); testArr.Add(1); testArr.Add(2); testArr.Add(4); testArr.Add(5); int sum = getSum(testArr); Console.WriteLine(sum);
Regex Words
using System.Text.RegularExpressions; string pattern = @"\w*"; Regex rg = new Regex(pattern); string phrase = "I am legend"; match match = rg.match(phrase); Console.WriteLine(match);
Regex Numbers
using System.Text.RegularExpressions; string pattern = @"[0-9]+"; Regex rg = new Regex(pattern); string phrase = "I am 23"; match match = rg.match(phrase); Console.WriteLine(match);
Regex Test
using System.Text.RegularExpressions; string pattern = @"Lee"; Regex rg = new Regex(pattern); string phrase = "Bob Lee"; bool match = rg.IsMatch(phrase); Console.WriteLine(match);
Regex Characters
using System.Text.RegularExpressions; string pattern = @"\W*\w*"; Regex rg = new Regex(pattern); string phrase = "##I am legend##"; match match = rg.match(phrase); Console.WriteLine(match);