Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
5. Generics
//5. Generics using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { //Generics is a mechanism to write classes that operate on some unknown type (generic type) //This way it is possible to write classes (like data structures) that could be used with many types without modifications //Example is List<T>, implemented once, works with any types in statically-safe manner (i.e. compiler throws error if you try adding bool to List<int> as opposed to runtime error) List<int> l1 = new List<int>(); List<Program> l2 = new List<Program>(); //l1.Add(true); //Let's build simple binary tree, where nodes' values can be of any comparable type. var tree = new BinaryTree<int>(10); tree.Add(13); tree.Add(12); tree.Add(14); tree.Add(9); var node = tree.Find(12); Console.WriteLine(node == null ? "not found" : node.Value.ToString()); } } public class BinaryTree<T> where T : IComparable //read BinaryTree of T. 'where' adds optional constraint to what generic type can be. In this case it must implement IComparable { Node<T> root { get; set; } public BinaryTree(T root) { if(root == null) throw new Exception("Null values are not allowed!"); this.root = new Node<T>(){ Value = root }; } public void Add(T val) { if(val == null) throw new Exception("Null values are not allowed!"); var root = this.root; while(true) { if(root.Value.CompareTo(val) >= 0) { if(root.Left == null) { root.Left = new Node<T>() { Value = val }; break; } else { root = root.Left; continue; } } else { if(root.Right == null) { root.Right = new Node<T> { Value = val }; break; } else { root = root.Right; continue; } } } } public Node<T> Find(T val) { return Find(val, root); } Node<T> Find(T val, Node<T> root) { if(root == null) return null; if(root.Value.CompareTo(val) == 0) { return root; } else if(root.Value.CompareTo(val) >= 0) { return Find(val, root.Left); } else { return Find(val, root.Right); } } public class Node<T> { public T Value { get; set; } public Node<T> Left { get; set; } public Node<T> Right { get; set; } } } }
run
|
edit
|
history
|
help
0
Jahongirochilov270@gmail.com
compiled prog
combine paths
asfdfsafasfsa
sdefrgthyjuiujyhtgrf
ss
code
הארות אופן שימוש
uniqueness
الحاسوب