using System; using System.Collections; using System.Collections.Generic; class Test { // Test variable scope IList v1 = new List(); // BAD: private scope void f() { var v2 = new List(); // BAD: local scope var x = v1.Contains(1); var y = v2.Contains(2); } public IList n1 = new List(); // GOOD: public protected IList n2 = new List(); // GOOD: protected void g() { n1.Contains(1); n2.Contains(2); } // Test initializer IList n3 = new List { 1, 2, 3 }; // GOOD: initialized IList v3; // BAD: unassigned void h() { n3.Contains(1); v3.Contains(1); } // Test variable uses void populate(IList v) { v.Add(1); } void f1() { var n4 = new List(); // GOOD: populated populate(n4); n4.Contains(1); var n5 = new List(); // GOOD: assigned n5 = new List { 1, 2, 3 }; n5.Contains(1); var v4 = new List(); // BAD: assigned only from empty list v4 = new List(); v4.Contains(1); var n5a = new List(); // GOOD: Not used } // Test attributes [Obsolete()] IList n6 = new List(); // GOOD: attribute void f3() { n6.Contains(1); } // Test reading methods void f4() { var v5 = new Dictionary(); // BAD v5.ContainsKey(1); v5.ContainsValue(1); v5.GetEnumerator(); var tmp = new HashSet(); var v6 = new HashSet(); // BAD v6.IsSubsetOf(tmp); v6.IsProperSubsetOf(tmp); v6.IsSupersetOf(tmp); v6.IsProperSupersetOf(tmp); var v7 = new LinkedList(); // BAD v7.Contains(1); var v8 = new Queue(); // BAD v8.Dequeue(); v8.Peek(); v8.ToArray(); var v9 = new Stack(); // BAD v9.Pop(); var v10 = new List(); // BAD: property access var x = v10.Count; } // Test writing methods void f5() { var n6 = new List(); // GOOD: Add method n6.Add(1); n6.Contains(1); // UnknownMethod // GOOD: other method var n7 = new List(); n7.GetType(); n7.Contains(1); } // Test indexed access void f6() { var v11 = new Dictionary(); // BAD: read by Index var x = v11[1]; var n12 = new Dictionary(); // GOOD: written by Index n12[1] = 2; x = n12[1]; } // Test foreach void f7() { var l1 = new List> { new List() }; foreach (var n13 in l1) // GOOD: from foreach { var x = n13.Count; } } // Test initialized with 'is' void f8(object arguments) { int c; if (arguments is IDictionary dict) // GOOD c = dict.Count; switch (arguments) { case IDictionary dict2: // GOOD c = dict2.Count; break; } } } // semmle-extractor-options: /r:System.Collections.dll