Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringclasses
50 values
testsource
stringclasses
6 values
language
stringclasses
6 values
prefix
stringlengths
16
3.39k
golden_completion
stringlengths
23
3.14k
suffix
stringlengths
0
2.68k
assertions
stringlengths
0
2.72k
category
stringclasses
6 values
1
devbench-api-usage
c_sharp
using System; using System.Collections.Concurrent; class Program { static int ComputeCount = 0; static int ComputeValue(string key) { ComputeCount++; return key.Length * 10; } static int GetOrCompute(ConcurrentDictionary<string, int> dict, string key) { return dict.Get...
static string DescribeGetOrCompute() { return "Uses ConcurrentDictionary.GetOrAdd(TKey, Func<TKey,TValue>) which " + "atomically returns the existing value if the key is present, or " + "invokes the valueFactory delegate to create and add a new value. " + "The valu...
static void Main() { var dict = new ConcurrentDictionary<string, int>(); ComputeCount = 0; int v1 = GetOrCompute(dict, "hello"); if (v1 != 50) throw new Exception("Expected 50"); if (ComputeCount != 1) throw new Exception("Factory should be called once"); int v...
string d1 = DescribeGetOrCompute().ToLower(); if (!d1.Contains("getoradd")) throw new Exception("Must mention GetOrAdd"); if (!d1.Contains("valuefactory") && !d1.Contains("factory") && !d1.Contains("delegate")) throw new Exception("Must mention factory/delegate"); if (!d1.Contains("atomically") && !d1.Contains("atomic"...
api_usage
2
devbench-api-usage
c_sharp
using System; using System.Collections.Generic; class Program { static SortedSet<int> GetRange(SortedSet<int> set, int lo, int hi) { return set.GetViewBetween(lo, hi); }
static string DescribeGetRange() { return "Uses SortedSet.GetViewBetween(lowerValue, upperValue) which returns " + "a live view (not a copy) of elements in [lowerValue, upperValue] — both " + "bounds are inclusive. The returned SortedSet is backed by the original: " ...
static void Main() { var set = new SortedSet<int> { 1, 3, 5, 7, 9, 11 }; var view = GetRange(set, 3, 9); if (view.Count != 4) throw new Exception($"Expected 4, got {view.Count}"); if (!view.Contains(3) || !view.Contains(9)) throw new Exception("Bounds inclusive"); view....
string d2 = DescribeGetRange().ToLower(); if (!d2.Contains("getviewbetween")) throw new Exception("Must mention GetViewBetween"); if (!(d2.Contains("live view") || d2.Contains("backed by") || d2.Contains("not a copy"))) throw new Exception("Must mention live view"); if (!d2.Contains("inclusive")) throw new Exception("M...
api_usage
3
devbench-api-usage
c_sharp
using System; using System.Text; class Program { static byte[] EncodeWithPreamble(string text) { Encoding utf8Bom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true); byte[] preamble = utf8Bom.GetPreamble(); byte[] encoded = utf8Bom.GetBytes(text); byte[] result = new byte...
static string DescribeEncodingBehavior() { return "Encoding.UTF8 is a UTF8Encoding instance with encoderShouldEmitUTF8Identifier " + "set to false — GetPreamble() returns an empty array, and GetBytes() produces " + "no BOM prefix (EF BB BF). Constructing new UTF8Encoding(true) ...
static void Main() { byte[] withBom = EncodeWithPreamble("Hi"); byte[] noBom = EncodeNoPreamble("Hi"); if (withBom.Length != noBom.Length + 3) throw new Exception("BOM is 3 bytes"); if (withBom[0] != 0xEF || withBom[1] != 0xBB || withBom[2] != 0xBF) throw new Excepti...
string d3 = DescribeEncodingBehavior().ToLower(); if (!(d3.Contains("ef bb bf") || d3.Contains("0xef") || d3.Contains("ef, bb, bf") || d3.Contains("0xef, 0xbb, 0xbf"))) throw new Exception("Must mention BOM bytes EF BB BF"); if (!(d3.Contains("getpreamble"))) throw new Exception("Must mention GetPreamble"); if (!(d3.Co...
api_usage
4
devbench-api-usage
c_sharp
using System; using System.Collections.Generic; class Program { static string ProcessQueue(PriorityQueue<string, int> pq) { var results = new List<string>(); while (pq.TryDequeue(out string? item, out int priority)) { results.Add($"{item}:{priority}"); } retu...
static string DescribeProcessQueue() { return "Uses PriorityQueue<TElement,TPriority>.TryDequeue which removes and returns " + "the element with the lowest priority value (min-heap). Returns false when the " + "queue is empty instead of throwing. Unlike Enqueue/Dequeue, TryDequ...
static void Main() { var pq = new PriorityQueue<string, int>(); pq.Enqueue("low", 3); pq.Enqueue("high", 1); pq.Enqueue("mid", 2); string result = ProcessQueue(pq); if (!result.StartsWith("high:1")) throw new Exception($"Min-heap expected, got {result}"); ...
string d4 = DescribeProcessQueue().ToLower(); if (!d4.Contains("trydequeue")) throw new Exception("Must mention TryDequeue"); if (!(d4.Contains("min-heap") || d4.Contains("lowest priority"))) throw new Exception("Must mention min-heap behavior"); if (!(d4.Contains("not stable") || d4.Contains("any order"))) throw new E...
api_usage
5
devbench-api-usage
c_sharp
using System; using System.Text.RegularExpressions; class Program { static (string year, string month, string day) ParseDate(string input) { var match = Regex.Match(input, @"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})"); if (!match.Success) throw new FormatException("Invalid date f...
static string DescribeParseDate() { return "Uses Regex.Match(string, string) which returns a single Match object " + "(never null — check Match.Success). Named capture groups (?<name>...) " + "are accessed via Match.Groups[string] returning a Group object whose " +...
static void Main() { var (y, m, d) = ParseDate("2024-03-15"); if (y != "2024" || m != "03" || d != "15") throw new Exception("Parsing failed"); bool threw = false; try { ParseDate("not-a-date"); } catch (FormatException) { threw = true; } if (!threw)...
string d5 = DescribeParseDate().ToLower(); if (!d5.Contains("regex.match")) throw new Exception("Must mention Regex.Match"); if (!(d5.Contains("named") && (d5.Contains("capture") || d5.Contains("group")))) throw new Exception("Must mention named capture groups"); if (!(d5.Contains("never null") || d5.Contains("match.su...
api_usage
6
devbench-api-usage
c_sharp
using System; using System.Linq; class Program { static string BuildPath(string[] segments) { return segments.Aggregate("root", (current, next) => current + "/" + next, result => result.ToUpper()); }
static string DescribeBuildPath() { return "Uses Enumerable.Aggregate<TSource,TAccumulate,TResult>(seed, func, resultSelector) " + "— the three-parameter overload. The seed ('root') is the initial accumulator value " + "and its type (TAccumulate) can differ from TSource. The fu...
static void Main() { string result = BuildPath(new[] { "usr", "local", "bin" }); if (result != "ROOT/USR/LOCAL/BIN") throw new Exception($"Expected ROOT/USR/LOCAL/BIN, got {result}"); string empty = BuildPath(new string[0]); if (empty != "ROOT") throw new Exception($"Empty shou...
string d6 = DescribeBuildPath().ToLower(); if (!d6.Contains("aggregate")) throw new Exception("Must mention Aggregate"); if (!(d6.Contains("seed") || d6.Contains("initial accumulator"))) throw new Exception("Must mention seed"); if (!(d6.Contains("resultselector") || d6.Contains("result selector") || d6.Contains("proje...
api_usage
7
devbench-api-usage
c_sharp
using System; using System.Text; class Program { static string JoinValues(string separator, params string[] values) { var sb = new StringBuilder(256); sb.AppendJoin(separator, values); return sb.ToString(); }
static string DescribeJoinValues() { return "Uses StringBuilder(int capacity) constructor to pre-allocate a 256-char " + "internal buffer, avoiding reallocations for small inputs. AppendJoin(string, " + "params object[]) appends each element separated by the separator in a sing...
static void Main() { string result = JoinValues(", ", "a", "b", "c"); if (result != "a, b, c") throw new Exception($"Expected 'a, b, c', got '{result}'"); string single = JoinValues("-", "only"); if (single != "only") throw new Exception($"Expected 'only', got '{single}'"); ...
string d7 = DescribeJoinValues().ToLower(); if (!d7.Contains("appendjoin")) throw new Exception("Must mention AppendJoin"); if (!(d7.Contains("capacity") || d7.Contains("pre-allocat") || d7.Contains("preallocat"))) throw new Exception("Must mention capacity/pre-allocation"); if (!(d7.Contains("in-place") || d7.Contains...
api_usage
8
devbench-api-usage
c_sharp
using System; using System.Collections.Generic; using System.Text.Json; class Program { static (string name, int age) ParsePerson(string json) { using JsonDocument doc = JsonDocument.Parse(json); JsonElement root = doc.RootElement; string name = root.GetProperty("name").GetString() ?? "...
static string DescribeParsePerson() { return "Uses JsonDocument.Parse(string) which parses JSON into a read-only DOM " + "backed by pooled memory from ArrayPool<byte>. JsonDocument implements " + "IDisposable — the using statement ensures pooled buffers are returned. " ...
static void Main() { var (name, age) = ParsePerson("{\"name\": \"Alice\", \"age\": 30}"); if (name != "Alice" || age != 30) throw new Exception("Parse failed"); bool threw = false; try { ParsePerson("{\"name\": \"Bob\"}"); } catch (KeyNotFoundException) { threw = true; ...
string d8 = DescribeParsePerson().ToLower(); if (!d8.Contains("jsondocument")) throw new Exception("Must mention JsonDocument"); if (!(d8.Contains("idisposable") || d8.Contains("disposable") || d8.Contains("using"))) throw new Exception("Must mention IDisposable"); if (!(d8.Contains("arraypool") || d8.Contains("pooled"...
api_usage
9
devbench-api-usage
c_sharp
using System; using System.Collections.Generic; class Program { static bool SafeInsert(Dictionary<string, int> dict, string key, int value) { return dict.TryAdd(key, value); } static void ForceInsert(Dictionary<string, int> dict, string key, int value) { dict.Add(key, value); }...
static string DescribeSafeInsert() { return "Uses Dictionary.TryAdd(TKey, TValue) which returns false without throwing " + "if the key already exists — unlike Add which throws ArgumentException for " + "duplicate keys. TryAdd is O(1) amortized for hash table insertion. " ...
static void Main() { var dict = new Dictionary<string, int>(); bool added1 = SafeInsert(dict, "x", 10); if (!added1) throw new Exception("First insert should succeed"); bool added2 = SafeInsert(dict, "x", 20); if (added2) throw new Exception("Duplicate insert should re...
string d9 = DescribeSafeInsert().ToLower(); if (!d9.Contains("tryadd")) throw new Exception("Must mention TryAdd"); if (!d9.Contains("argumentexception")) throw new Exception("Must mention ArgumentException for duplicate keys"); if (!(d9.Contains("false") && (d9.Contains("without throwing") || d9.Contains("does not thr...
api_usage
10
devbench-api-usage
c_sharp
using System; using System.Threading.Tasks; using System.Collections.Generic; class Program { static async Task<int[]> RunAll(params Func<Task<int>>[] factories) { var tasks = new List<Task<int>>(); foreach (var f in factories) tasks.Add(f()); return await Task.WhenAll(tasks...
static string DescribeRunAll() { return "Uses Task.WhenAll(IEnumerable<Task<TResult>>) which returns a single Task<TResult[]> " + "that completes when ALL input tasks complete. The result array preserves the " + "original task order (not completion order). If any task faults, W...
static async Task Main() { int[] results = await RunAll( async () => { await Task.Delay(10); return 1; }, async () => { await Task.Delay(5); return 2; }, async () => { return 3; } ); if (results.Length != 3) throw new Exception("Expected 3 results");...
string d10 = DescribeRunAll().ToLower(); if (!d10.Contains("whenall")) throw new Exception("Must mention WhenAll"); if (!(d10.Contains("order") && (d10.Contains("preserv") || d10.Contains("original")))) throw new Exception("Must mention order preservation"); if (!d10.Contains("aggregateexception")) throw new Exception(...
api_usage
11
devbench-api-usage
c_sharp
using System; using System.Buffers; namespace ApiTask11 { public class Program { public static int SumWithRentedBuffer(int[] source) { int[] buffer = ArrayPool<int>.Shared.Rent(source.Length); try { Array.Copy(source, buffer, source.Length); ...
public static string DescribeSumWithRentedBuffer() { return "Rents a buffer from ArrayPool<int>.Shared.Rent(minimumLength) which may " + "return an array LARGER than requested (power-of-two sizing). Copies source " + "via Array.Copy then sums only source.Len...
public static void Main(string[] args) { int result = SumWithRentedBuffer(new int[] { 1, 2, 3, 4, 5 }); if (result != 15) throw new Exception("Sum failed"); string desc = DescribeSumWithRentedBuffer(); if (string.IsNullOrEmpty(desc)) throw new Exception(...
string d11 = ApiTask11.Program.DescribeSumWithRentedBuffer().ToLower(); if (!d11.Contains("larger than requested") && !d11.Contains("bigger than") && !d11.Contains("may return a larger") && !d11.Contains("power-of-two") && !d11.Contains("power of two")) throw new Exception("Must mention buffer may be larger than reques...
api_usage
12
devbench-api-usage
c_sharp
using System; namespace ApiTask12 { public class Program { public static int SumMiddleThird(ReadOnlySpan<int> data) { int start = data.Length / 3; int end = 2 * data.Length / 3; ReadOnlySpan<int> slice = data.Slice(start, end - start); int sum = 0...
public static string DescribeSumMiddleThird() { return "Uses ReadOnlySpan<int> which is a stack-only ref struct that cannot " + "be boxed, stored on the heap, or used in async methods. Slice(start, length) " + "creates a new ReadOnlySpan over the same underl...
public static void Main(string[] args) { int[] data = { 10, 20, 30, 40, 50, 60 }; int result = SumMiddleThird(data); if (result != 70) throw new Exception($"Expected 70, got {result}"); string desc = DescribeSumMiddleThird(); if (string.IsNul...
string d12 = ApiTask12.Program.DescribeSumMiddleThird().ToLower(); if (!d12.Contains("ref struct")) throw new Exception("Must mention ref struct"); if (!d12.Contains("stack") || (!d12.Contains("heap") && !d12.Contains("boxed"))) throw new Exception("Must mention stack-only / cannot be on heap"); if (!d12.Contains("zero...
api_usage
13
devbench-api-usage
c_sharp
using System; using System.Numerics; namespace ApiTask13 { public class Program { public static BigInteger Factorial(int n) { BigInteger result = BigInteger.One; for (int i = 2; i <= n; i++) result = BigInteger.Multiply(result, new BigInteger(i)); ...
public static string DescribeFactorial() { return "Uses System.Numerics.BigInteger which is an immutable, arbitrary-precision " + "signed integer — no overflow is possible. BigInteger.One is a static readonly " + "field (not a property) representing the valu...
public static void Main(string[] args) { BigInteger f10 = Factorial(10); if (f10 != 3628800) throw new Exception("10! wrong"); BigInteger f20 = Factorial(20); if (f20 != BigInteger.Parse("2432902008176640000")) throw new Exception("20! wrong"); ...
string d13 = ApiTask13.Program.DescribeFactorial().ToLower(); if (!d13.Contains("immutable")) throw new Exception("Must mention immutable"); if (!d13.Contains("arbitrary-precision") && !d13.Contains("arbitrary precision") && !d13.Contains("unlimited precision")) throw new Exception("Must mention arbitrary-precision"); ...
api_usage
14
devbench-api-usage
c_sharp
using System; using System.Net; using System.Net.Sockets; namespace ApiTask14 { public class Program { public static string ClassifyAddress(string input) { if (!IPAddress.TryParse(input, out IPAddress addr)) return "INVALID"; if (addr.AddressFamily == Add...
public static string DescribeClassifyAddress() { return "Uses IPAddress.TryParse which returns bool and sets the out parameter " + "to null on failure (not IPAddress.None). AddressFamily is an enum with " + "InterNetwork for IPv4 and InterNetworkV6 for IPv6 ...
public static void Main(string[] args) { if (ClassifyAddress("10.0.0.1") != "PRIVATE_A") throw new Exception("10.x fail"); if (ClassifyAddress("127.0.0.1") != "LOOPBACK") throw new Exception("Loopback fail"); if (ClassifyAddress("::1") != "IPv6") throw new Exception(...
string d14 = ApiTask14.Program.DescribeClassifyAddress().ToLower(); if (!d14.Contains("tryparse") || !d14.Contains("bool")) throw new Exception("Must mention TryParse returns bool"); if (!d14.Contains("null") && !d14.Contains("out parameter")) throw new Exception("Must mention out param is null on failure"); if (!d14.C...
api_usage
15
devbench-api-usage
c_sharp
using System; using System.Collections.Generic; namespace ApiTask15 { public class Program { public static (int symDiffCount, int interCount, bool isProperSubset) AnalyzeSets(int[] a, int[] b) { var setA = new HashSet<int>(a); var setB = new HashSet<int>(b); ...
public static string DescribeAnalyzeSets() { return "Uses HashSet<int> set-theoretic methods. SymmetricExceptWith MUTATES the " + "set in-place to contain only elements in one set or the other, not both — " + "it does NOT return a new HashSet. IntersectWith ...
public static void Main(string[] args) { var (sd, ic, ps) = AnalyzeSets(new[] {1,2,3}, new[] {2,3,4}); if (sd != 2) throw new Exception($"SymDiff count: expected 2, got {sd}"); if (ic != 2) throw new Exception($"Intersect count: expected 2, got {ic}"); if...
string d15 = ApiTask15.Program.DescribeAnalyzeSets().ToLower(); if (!d15.Contains("mutate") && !d15.Contains("in-place") && !d15.Contains("in place") && !d15.Contains("modifies")) throw new Exception("Must mention in-place mutation"); if (!d15.Contains("symmetricexceptwith") && !d15.Contains("symmetric except")) throw ...
api_usage
16
devbench-api-usage
c_sharp
using System; using System.IO; namespace ApiTask16 { public class Program { public static string GetConfigPath(string appName) { string envOverride = Environment.GetEnvironmentVariable("CONFIG_DIR"); if (envOverride != null) return Path.Combine(envOverrid...
public static string DescribeGetConfigPath() { return "Uses Environment.GetEnvironmentVariable which returns null (not empty " + "string) when the variable does not exist — this differs from " + "GetEnvironmentVariable(name, EnvironmentVariableTarget) overlo...
public static void Main(string[] args) { Environment.SetEnvironmentVariable("CONFIG_DIR", "/tmp/cfg"); string result = GetConfigPath("myapp"); string expected = Path.Combine("/tmp/cfg", "myapp"); if (result != expected) throw new Exception($"Expected {exp...
string d16 = ApiTask16.Program.DescribeGetConfigPath().ToLower(); if (!d16.Contains("null") || d16.Contains("empty string") && !d16.Contains("returns null")) throw new Exception("Must mention GetEnvironmentVariable returns null when not found"); if (!d16.Contains("environmentvariabletarget") && !d16.Contains("machine")...
api_usage
17
devbench-api-usage
c_sharp
using System; using System.IO; using System.Text; namespace ApiTask17 { public class Program { public static byte[] PackRecord(int id, string name, double score) { using var ms = new MemoryStream(); using (var bw = new BinaryWriter(ms, Encoding.UTF8, leaveOpen: true)) ...
public static string DescribePackRecord() { return "Uses BinaryWriter.Write(int) which writes 4 bytes in little-endian order. " + "BinaryWriter.Write(string) writes a length-prefixed UTF-8 string: the " + "length is encoded as a 7-bit variable-length integer...
public static void Main(string[] args) { byte[] packed = PackRecord(42, "Alice", 95.5); var (id, name, score) = UnpackRecord(packed); if (id != 42) throw new Exception("id mismatch"); if (name != "Alice") throw new Exception("name mismatch"); ...
string d17 = ApiTask17.Program.DescribePackRecord().ToLower(); if (!d17.Contains("little-endian") && !d17.Contains("little endian")) throw new Exception("Must mention little-endian byte order"); if (!d17.Contains("length-prefix") && !d17.Contains("length prefix") && !d17.Contains("leb128") && !d17.Contains("7-bit")) th...
api_usage
18
devbench-api-usage
c_sharp
using System; using System.Diagnostics; using System.Threading; namespace ApiTask18 { public class Program { public static double MeasureElapsedMs(Action action) { long start = Stopwatch.GetTimestamp(); action(); long end = Stopwatch.GetTimestamp(); ...
public static string DescribeMeasureElapsedMs() { return "Uses Stopwatch.GetTimestamp() which is a static method returning the " + "current value of the high-resolution performance counter as a long. " + "Stopwatch.Frequency is a static readonly field giving...
public static void Main(string[] args) { double elapsed = MeasureElapsedMs(() => Thread.Sleep(50)); if (elapsed < 30 || elapsed > 500) throw new Exception($"Elapsed {elapsed}ms out of range"); string desc = DescribeMeasureElapsedMs(); if (string.IsNullOr...
string d18 = ApiTask18.Program.DescribeMeasureElapsedMs().ToLower(); if (!d18.Contains("gettimestamp") && !d18.Contains("get timestamp")) throw new Exception("Must mention GetTimestamp"); if (!d18.Contains("frequency")) throw new Exception("Must mention Frequency field"); if (!d18.Contains("platform-dependent") && !d18...
api_usage
19
devbench-api-usage
c_sharp
using System; namespace ApiTask19 { [Flags] public enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4, All = Read | Write | Execute } public class Program { public static string CheckPermissions(string input) { if (...
public static string DescribeCheckPermissions() { return "Uses Enum.TryParse<T>(string, bool ignoreCase, out T result) which " + "returns true even for integer strings ('3') and undefined combinations — " + "TryParse succeeds for ANY valid integer, not just ...
public static void Main(string[] args) { if (CheckPermissions("Read") != "Read") throw new Exception("Read parse fail"); if (CheckPermissions("read") != "Read") throw new Exception("Case-insensitive fail"); if (CheckPermissions("garbage") != "INVALID") throw new Exce...
string d19 = ApiTask19.Program.DescribeCheckPermissions().ToLower(); if (!d19.Contains("tryparse")) throw new Exception("Must mention TryParse"); if (!d19.Contains("integer string") && !d19.Contains("integer value") && !d19.Contains("any valid integer") && !d19.Contains("numeric")) throw new Exception("Must mention Try...
api_usage
20
devbench-api-usage
c_sharp
using System; using System.Text; namespace ApiTask20 { public class Program { public static string EncodeToBase64(string text) { byte[] bytes = Encoding.UTF8.GetBytes(text); return Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks); } ...
public static string DescribeBase64Operations() { return "Uses Convert.ToBase64String with Base64FormattingOptions.InsertLineBreaks " + "which inserts a line break every 76 characters (MIME standard RFC 2045). " + "Without the option, no line breaks are inse...
public static void Main(string[] args) { string encoded = EncodeToBase64("Hello, World!"); string decoded = DecodeFromBase64(encoded.Replace("\r\n", "")); if (decoded != "Hello, World!") throw new Exception("Roundtrip failed"); string simple = Convert.To...
string d20 = ApiTask20.Program.DescribeBase64Operations().ToLower(); if (!d20.Contains("insertlinebreaks") && !d20.Contains("insert line breaks") && !d20.Contains("line break")) throw new Exception("Must mention InsertLineBreaks option"); if (!d20.Contains("76") && !d20.Contains("seventy-six")) throw new Exception("Mus...
api_usage
21
devbench-api-usage
c_sharp
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; public class AUTask21 { public static List<string> ExtractDescendants(string xml, string tagName) { XDocument doc = XDocument.Parse(xml); return doc.Descendants(tagName) .Select(e => e.Va...
public static string DescribeExtractDescendants() { return "Parses XML string using XDocument.Parse(string) which returns an XDocument. " + "Calls Descendants(XName) to find all elements matching tagName at any depth. " + "Descendants performs a depth-first traversal of the ent...
static void Main() { string xml = "<root><a><b>hello</b><b>world</b></a><b>outer</b></root>"; var results = ExtractDescendants(xml, "b"); if (!(results.Count == 3)) throw new Exception("Expected 3 descendants"); if (!(results[0] == "hello")) throw new Exception("First should be ...
string d21 = AUTask21.DescribeExtractDescendants().ToLower(); if (!d21.Contains("xdocument.parse")) throw new Exception("Must mention XDocument.Parse"); if (!d21.Contains("descendants")) throw new Exception("Must mention Descendants method"); if (!d21.Contains("depth-first") && !d21.Contains("any depth")) throw new Exc...
api_usage
22
devbench-api-usage
c_sharp
using System; using System.Reflection; public class AUTask22 { public static int Add(int a, int b) => a + b; public static object InvokeByName(Type type, string methodName, object[] args) { MethodInfo mi = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); i...
public static string DescribeInvokeByName() { return "Retrieves a MethodInfo via Type.GetMethod(string, BindingFlags) with " + "BindingFlags.Public | BindingFlags.Static to search only public static methods. " + "GetMethod returns null if no matching method exists, so the code ...
static void Main() { object result = InvokeByName(typeof(AUTask22), "Add", new object[] { 3, 4 }); if (!((int)result == 7)) throw new Exception("Expected 7"); } }
string d22 = AUTask22.DescribeInvokeByName().ToLower(); if (!d22.Contains("getmethod")) throw new Exception("Must mention GetMethod"); if (!d22.Contains("bindingflags")) throw new Exception("Must mention BindingFlags"); if (!(d22.Contains("public") && d22.Contains("static"))) throw new Exception("Must mention Public an...
api_usage
23
devbench-api-usage
c_sharp
using System; using System.Reflection; [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class RateLimitAttribute : Attribute { public int MaxCalls { get; } public int PeriodSeconds { get; } public RateLimitAttribute(int maxCalls, int periodSeconds) { Ma...
public static string DescribeGetRateLimit() { return "Uses MethodInfo.GetCustomAttribute<T>(bool) generic method with inherit=false " + "to retrieve only directly-applied attributes, not inherited ones. " + "The RateLimitAttribute is decorated with AttributeUsage specifying " ...
static void Main() { var method = typeof(AUTask23).GetMethod("ApiEndpoint"); var (maxCalls, period) = GetRateLimit(method); if (!(maxCalls == 100)) throw new Exception("Expected 100 max calls"); if (!(period == 60)) throw new Exception("Expected 60 second period"); } }
string d23 = AUTask23.DescribeGetRateLimit().ToLower(); if (!d23.Contains("getcustomattribute")) throw new Exception("Must mention GetCustomAttribute"); if (!d23.Contains("inherit")) throw new Exception("Must mention inherit parameter"); if (!d23.Contains("false")) throw new Exception("Must mention inherit=false"); if ...
api_usage
24
devbench-api-usage
c_sharp
using System; using System.Collections.Generic; using System.Collections.ObjectModel; public class AUTask24 { public static ReadOnlyCollection<int> WrapAsReadOnly(List<int> source) { return source.AsReadOnly(); }
public static string DescribeWrapAsReadOnly() { return "Calls List<T>.AsReadOnly() which returns a ReadOnlyCollection<T> that is " + "a thin wrapper around the original list, not a copy. Mutations to the " + "underlying source list are visible through the ReadOnlyCollection bec...
static void Main() { var source = new List<int> { 1, 2, 3 }; var ro = WrapAsReadOnly(source); if (!(ro.Count == 3)) throw new Exception("Expected count 3"); source.Add(4); if (!(ro.Count == 4)) throw new Exception("ReadOnly should reflect source mutation"); bool ...
string d24 = AUTask24.DescribeWrapAsReadOnly().ToLower(); if (!d24.Contains("asreadonly")) throw new Exception("Must mention AsReadOnly method"); if (!(d24.Contains("wrapper") || d24.Contains("wraps"))) throw new Exception("Must mention wrapper semantics"); if (!(d24.Contains("not a copy") || d24.Contains("reference"))...
api_usage
25
devbench-api-usage
c_sharp
using System; using System.Threading; public class AUTask25 { private static int _initCount = 0; public static Lazy<string> CreateExpensiveResource() { return new Lazy<string>(() => { Interlocked.Increment(ref _initCount); return "Resource_" + _initCount; },...
public static string DescribeLazyInit() { return "Creates a Lazy<T> with a Func<T> factory and LazyThreadSafetyMode.ExecutionAndPublication. " + "ExecutionAndPublication ensures exactly one thread executes the factory; other threads " + "block until initialization completes, th...
static void Main() { var lazy = CreateExpensiveResource(); if (!(lazy.IsValueCreated == false)) throw new Exception("Should not be created yet"); string val1 = lazy.Value; string val2 = lazy.Value; if (!(val1 == val2)) throw new Exception("Should return same cached value...
string d25 = AUTask25.DescribeLazyInit().ToLower(); if (!d25.Contains("executionandpublication")) throw new Exception("Must mention ExecutionAndPublication mode"); if (!(d25.Contains("exactly one thread") || d25.Contains("single thread"))) throw new Exception("Must mention single-thread execution guarantee"); if (!(d25...
api_usage
26
devbench-api-usage
c_sharp
using System; using System.IO; using System.IO.Compression; using System.Text; public class AUTask26 { public static byte[] CompressString(string text) { byte[] raw = Encoding.UTF8.GetBytes(text); using (var output = new MemoryStream()) { using (var gzip = new GZipStream(out...
public static string DescribeCompression() { return "CompressString converts text to bytes via Encoding.UTF8.GetBytes, then wraps a " + "MemoryStream with GZipStream(Stream, CompressionMode.Compress, leaveOpen: true). " + "leaveOpen: true prevents GZipStream.Dispose from closin...
static void Main() { string original = "Hello, GZip compression test!"; byte[] compressed = CompressString(original); if (!(compressed.Length > 0)) throw new Exception("Compressed should be non-empty"); string decompressed = DecompressToString(compressed); if (!(decompre...
string d26 = AUTask26.DescribeCompression().ToLower(); if (!d26.Contains("gzipstream")) throw new Exception("Must mention GZipStream"); if (!d26.Contains("compressionmode.compress")) throw new Exception("Must mention CompressionMode.Compress"); if (!d26.Contains("leaveopen")) throw new Exception("Must mention leaveOpen...
api_usage
27
devbench-api-usage
c_sharp
using System; using System.Threading; public class AUTask27 { private static int _value = 0; public static int AtomicMax(ref int location, int comparand) { int initial, computed; do { initial = location; computed = Math.Max(initial, comparand); } ...
public static string DescribeAtomicMax() { return "Implements a lock-free atomic maximum using Interlocked.CompareExchange(ref int, int, int) " + "in a CAS (compare-and-swap) spin loop. The loop reads the current value into 'initial', " + "computes Math.Max(initial, comparand),...
static void Main() { _value = 5; int result = AtomicMax(ref _value, 10); if (!(result == 10)) throw new Exception("Expected max 10"); if (!(_value == 10)) throw new Exception("Location should be 10"); result = AtomicMax(ref _value, 3); if (!(result == 10)) throw ...
string d27 = AUTask27.DescribeAtomicMax().ToLower(); if (!d27.Contains("compareexchange")) throw new Exception("Must mention CompareExchange"); if (!(d27.Contains("cas") || d27.Contains("compare-and-swap") || d27.Contains("compare and swap"))) throw new Exception("Must mention CAS pattern"); if (!(d27.Contains("spin") ...
api_usage
28
devbench-api-usage
c_sharp
using System; public class AUTask28 { public static double NextUp(double value) { return Math.BitIncrement(value); } public static double NextDown(double value) { return Math.BitDecrement(value); } public static double FusedMulAdd(double x, double y, double z) { ...
public static string DescribeFloatOps() { return "NextUp uses Math.BitIncrement(double) which returns the smallest double value " + "that is greater than the argument. It increments the binary representation by " + "one ULP (unit in the last place). For positive infinity, it re...
static void Main() { double up = NextUp(1.0); if (!(up > 1.0)) throw new Exception("BitIncrement should be > 1.0"); if (!(up < 1.0 + 1e-10)) throw new Exception("BitIncrement should be very close to 1.0"); double down = NextDown(1.0); if (!(down < 1.0)) throw new Excepti...
string d28 = AUTask28.DescribeFloatOps().ToLower(); if (!d28.Contains("bitincrement")) throw new Exception("Must mention BitIncrement"); if (!d28.Contains("bitdecrement")) throw new Exception("Must mention BitDecrement"); if (!(d28.Contains("ulp") || d28.Contains("unit in the last place"))) throw new Exception("Must me...
api_usage
29
devbench-api-usage
c_sharp
using System; public class AUTask29 { public static WeakReference<object> CreateWeakRef(object target) { return new WeakReference<object>(target, trackResurrection: false); } public static bool TryGetTarget(WeakReference<object> weakRef, out object target) { return weakRef.TryGetTa...
public static string DescribeWeakReference() { return "Creates a WeakReference<T> with trackResurrection: false, meaning the reference " + "becomes invalid once the target is finalized (short weak reference). " + "TryGetTarget(out T) atomically checks if the target is still ali...
static void Main() { var obj = new object(); var wr = CreateWeakRef(obj); object target; if (!(TryGetTarget(wr, out target))) throw new Exception("Should find live target"); if (!(ReferenceEquals(target, obj))) throw new Exception("Should be same object"); var ne...
string d29 = AUTask29.DescribeWeakReference().ToLower(); if (!d29.Contains("trackresurrection")) throw new Exception("Must mention trackResurrection parameter"); if (!(d29.Contains("short weak") || d29.Contains("finalized"))) throw new Exception("Must mention short weak reference or finalization semantics"); if (!d29.C...
api_usage
30
devbench-api-usage
c_sharp
using System; using System.Xml.Linq; using System.Linq; public class AUTask30 { private static readonly XNamespace Ns = "http://example.com/data"; public static XDocument BuildDocument(string rootName, (string name, string value)[] items) { var root = new XElement(Ns + rootName, new XA...
public static string DescribeBuildDocument() { return "Constructs an XDocument with XDeclaration('1.0', 'utf-8', 'yes') where 'yes' is " + "the standalone flag. Creates root XElement using XNamespace + string operator to produce " + "a qualified XName in the namespace. Adds XAt...
static void Main() { var items = new (string, string)[] { ("item", "A"), ("item", "B") }; XDocument doc = BuildDocument("root", items); string decl = GetDeclarationString(doc); if (!decl.Contains("utf-8")) throw new Exception("Declaration should contain utf-8"); if (!dec...
string d30 = AUTask30.DescribeBuildDocument().ToLower(); if (!d30.Contains("xdeclaration")) throw new Exception("Must mention XDeclaration"); if (!d30.Contains("standalone")) throw new Exception("Must mention standalone flag"); if (!d30.Contains("xnamespace")) throw new Exception("Must mention XNamespace"); if (!(d30.C...
api_usage
31
devbench-api-usage
c_sharp
using System; class Program { static Uri ParseAbsoluteUri(string input) { Uri result; bool ok = Uri.TryCreate(input, UriKind.Absolute, out result); if (!ok) return null; return result; } static string GetIdnHost(Uri uri) { return uri.GetComponents(UriCompone...
static string DescribeParseAbsoluteUri() { return "Uses Uri.TryCreate(string, UriKind.Absolute, out Uri) which returns false " + "for relative URIs or malformed input without throwing UriFormatException. " + "UriKind.Absolute requires a scheme (http, ftp, etc.) — schemeless str...
static void Main() { Uri u = ParseAbsoluteUri("http://Example.COM/path?q=1"); if (u == null) throw new Exception("Should parse valid absolute URI"); if (u.Scheme != "http") throw new Exception("Scheme should be http"); if (u.Host != "example.com") throw new Exception("Host shoul...
string d31 = Program.DescribeParseAbsoluteUri().ToLower(); if (!d31.Contains("urikind.absolute") && !d31.Contains("urikind absolute")) throw new Exception("Must mention UriKind.Absolute"); if (!d31.Contains("uriformatexception") && !d31.Contains("without throwing")) throw new Exception("Must mention no exception thrown...
api_usage
32
devbench-api-usage
c_sharp
using System; class Program { static int CompareVersions(string a, string b) { Version va = Version.Parse(a); Version vb = Version.Parse(b); return va.CompareTo(vb); } static bool IsPrerelease(string ver) { Version v = Version.Parse(ver); return v.Revision =...
static string DescribeCompareVersions() { return "Version.Parse(string) parses 'major.minor[.build[.revision]]' where " + "major and minor are required. Unparsed components default to -1 (not 0), " + "so '1.0' has Build=-1 and Revision=-1. CompareTo compares component by " ...
static void Main() { if (CompareVersions("2.0", "1.9") <= 0) throw new Exception("2.0 > 1.9"); if (CompareVersions("1.0", "1.0.0") >= 0) throw new Exception("1.0 < 1.0.0 because Build -1 < 0"); if (!IsPrerelease("1.0")) throw new Exception("1.0 has Revision -1"); if (IsPrereleas...
string d32 = Program.DescribeCompareVersions().ToLower(); if (!d32.Contains("-1")) throw new Exception("Must mention -1 default for undefined components"); if (!d32.Contains("not 0") && !d32.Contains("not zero")) throw new Exception("Must clarify defaults are -1, not 0"); if (!(d32.Contains("1.0") && d32.Contains("1.0....
api_usage
33
devbench-api-usage
c_sharp
using System; class Program { static void Main() { int original = 0x01020304;
byte[] bytes = BitConverter.GetBytes(original); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } int restored = BitConverter.ToInt32(BitConverter.IsLittleEndian ? GetReversed(bytes) : bytes, 0);
if (restored != original) throw new Exception("Round-trip failed: " + restored); // Verify big-endian byte order after our reversal if (BitConverter.IsLittleEndian) { if (bytes[0] != 0x01) throw new Exception("Expected MSB first after reverse"); if (bytes[3] != ...
byte[] testBytes = BitConverter.GetBytes((int)0x0A0B0C0D); if (BitConverter.IsLittleEndian) { if (testBytes[0] != 0x0D) throw new Exception("Little-endian: LSB should be first byte"); if (testBytes[3] != 0x0A) throw new Exception("Little-endian: MSB should be last byte"); } int roundTrip = BitConverter.ToInt32(...
api_usage
34
devbench-api-usage
c_sharp
using System; class Program { static int FindOrInsertionPoint(int[] sorted, int value) { int idx = Array.BinarySearch(sorted, value); return idx >= 0 ? idx : ~idx; }
static string DescribeFindOrInsertionPoint() { return "Uses Array.BinarySearch(Array, Object) which performs O(log n) binary search " + "on a SORTED array. Returns the zero-based index if found. If NOT found, returns " + "the bitwise complement (~) of the index of the next elem...
static void Main() { int[] arr = { 1, 3, 5, 7, 9 }; if (FindOrInsertionPoint(arr, 5) != 2) throw new Exception("Should find 5 at index 2"); if (FindOrInsertionPoint(arr, 4) != 2) throw new Exception("4 would insert at index 2"); if (FindOrInsertionPoint(arr, 0) != 0) throw new E...
string d34 = Program.DescribeFindOrInsertionPoint().ToLower(); if (!d34.Contains("bitwise complement") && !d34.Contains("~")) throw new Exception("Must mention bitwise complement"); if (!d34.Contains("sorted")) throw new Exception("Must mention sorted requirement"); if (!d34.Contains("undefined") && !d34.Contains("not ...
api_usage
35
devbench-api-usage
c_sharp
using System; using System.Data; class Program { static void Main() { DataTable table = new DataTable("Sales"); table.Columns.Add("Product", typeof(string)); table.Columns.Add("Qty", typeof(int)); table.Columns.Add("Price", typeof(decimal));
table.Columns.Add("Total", typeof(decimal), "Qty * Price"); table.Rows.Add("Widget", 5, 3.50m); table.Rows.Add("Gadget", 2, 12.00m); table.Rows.Add("Widget", 3, 3.50m); DataRow[] widgets = table.Select("Product = 'Widget'", "Total DESC"); decimal firstTotal = (decimal)w...
if (widgets.Length != 2) throw new Exception("Should find 2 Widget rows, got " + widgets.Length); if (firstTotal != 17.50m) throw new Exception("First Widget total should be 17.50 (5*3.50), got " + firstTotal); decimal secondTotal = (decimal)widgets[1]["Total"]; if (secondTotal != 10.50...
DataTable dt = new DataTable(); dt.Columns.Add("A", typeof(int)); dt.Columns.Add("B", typeof(int)); dt.Columns.Add("C", typeof(int), "A + B"); dt.Rows.Add(1, 2); if ((int)dt.Rows[0]["C"] != 3) throw new Exception("Expression column should compute"); dt.Rows[0]["A"] = 10; if ((int)dt.Rows[0]["C"] != 12) throw new Except...
api_usage
36
devbench-api-usage
c_sharp
using System; class Program { static void SafeCopy(Array src, int srcIdx, Array dst, int dstIdx, int len) { Array.ConstrainedCopy(src, srcIdx, dst, dstIdx, len); } static void RegularCopy(Array src, int srcIdx, Array dst, int dstIdx, int len) { Array.Copy(src, srcIdx, dst, dstIdx, ...
static string DescribeSafeCopy() { return "Array.ConstrainedCopy provides atomicity: either ALL elements are copied or " + "NONE are (the destination is unchanged on failure). This differs from Array.Copy " + "which may leave the destination partially modified if an exception o...
static void Main() { int[] src = { 1, 2, 3, 4, 5 }; int[] dst = { 0, 0, 0, 0, 0 }; SafeCopy(src, 1, dst, 0, 3); if (dst[0] != 2 || dst[1] != 3 || dst[2] != 4) throw new Exception("ConstrainedCopy failed"); if (dst[3] != 0) throw new Exception("Should not modify beyond le...
string d36 = Program.DescribeSafeCopy().ToLower(); if (!d36.Contains("atomic") && !d36.Contains("all or nothing") && !d36.Contains("all elements")) throw new Exception("Must mention atomicity guarantee"); if (!d36.Contains("array.copy")) throw new Exception("Must contrast with Array.Copy"); if (!d36.Contains("partially...
api_usage
37
devbench-api-usage
c_sharp
using System; using System.Collections.Specialized; class Program { static void Main() { NameValueCollection nvc = new NameValueCollection();
nvc.Add("color", "red"); nvc.Add("color", "blue"); nvc.Add("size", "large"); string colors = nvc.Get("color"); string[] colorArray = nvc.GetValues("color"); int keyCount = nvc.Count;
// Get returns comma-separated for multiple values if (colors != "red,blue") throw new Exception("Get should return 'red,blue', got: " + colors); if (colorArray.Length != 2) throw new Exception("GetValues should return 2 items"); if (colorArray[0] != "red" || colorArray[1] != "blue") th...
NameValueCollection test = new NameValueCollection(); test.Add("k", "v1"); test.Add("k", "v2"); test.Add("k", "v3"); if (test.Get("k") != "v1,v2,v3") throw new Exception("Get should comma-join multiple values"); if (test.Count != 1) throw new Exception("Count counts keys, not values"); test.Set("k", "only"); if (test.G...
api_usage
38
devbench-api-usage
c_sharp
using System; class Program { static void GrowArray(ref int[] arr, int newSize) { Array.Resize(ref arr, newSize); }
static string DescribeGrowArray() { return "Array.Resize<T>(ref T[], int) does NOT resize the array in-place. It allocates " + "a NEW array of the specified size, copies elements from the old array (up to " + "Math.Min(old.Length, newSize)), and assigns the new array to the ref...
static void Main() { int[] original = { 1, 2, 3 }; int[] alias = original; GrowArray(ref original, 5); // Original reference now points to new array if (original.Length != 5) throw new Exception("Should be length 5"); if (original[3] != 0) throw new Exception("N...
string d38 = Program.DescribeGrowArray().ToLower(); if (!d38.Contains("new array") && !d38.Contains("allocate")) throw new Exception("Must mention new array allocation"); if (!d38.Contains("not") && !d38.Contains("does not")) throw new Exception("Must mention does NOT resize in-place"); if (!d38.Contains("ref")) throw ...
api_usage
39
devbench-api-usage
c_sharp
using System; class Program { static void Main() { Uri uri = new Uri("http://example.com:8080/path/to/resource?key=val&foo=bar#section2");
string host = uri.Host; int port = uri.Port; string path = uri.AbsolutePath; string query = uri.Query; string fragment = uri.Fragment; string authority = uri.Authority; string pathAndQuery = uri.PathAndQuery;
if (host != "example.com") throw new Exception("Host wrong: " + host); if (port != 8080) throw new Exception("Port wrong: " + port); if (path != "/path/to/resource") throw new Exception("AbsolutePath wrong: " + path); // Query includes the leading '?' if (query != "?key=val&foo=...
Uri u39 = new Uri("https://user:pass@host.com:443/a/b?x=1#frag"); if (u39.Port != 443) throw new Exception("Port should be 443"); if (u39.IsDefaultPort != true) throw new Exception("443 is default for https"); if (!u39.Query.StartsWith("?")) throw new Exception("Query must start with ?"); if (!u39.Fragment.StartsWith("...
api_usage
40
devbench-api-usage
c_sharp
using System; using System.Collections.Specialized; class Program { static StringDictionary CreateLookup(string[] keys, string[] values) { StringDictionary sd = new StringDictionary(); for (int i = 0; i < keys.Length; i++) { sd.Add(keys[i], values[i]); } retu...
static string DescribeCreateLookup() { return "Uses StringDictionary which automatically LOWERCASES all keys on Add, " + "ContainsKey, and indexer access. 'Hello' and 'hello' map to the SAME entry — " + "Add('Hello','x') followed by Add('hello','y') throws ArgumentException for...
static void Main() { StringDictionary sd = CreateLookup( new[] { "Name", "COLOR", "Size" }, new[] { "Alice", "Red", "Large" } ); // Keys are lowercased if (sd["name"] != "Alice") throw new Exception("Should find 'name' (lowered from 'Name')"); if...
string d40 = Program.DescribeCreateLookup().ToLower(); if (!d40.Contains("lowercase") && !d40.Contains("lower-case") && !d40.Contains("lowered")) throw new Exception("Must mention key lowercasing"); if (!d40.Contains("case-sensitive") && !d40.Contains("case sensitive")) throw new Exception("Must mention case sensitivit...
api_usage
41
devbench-api-usage
c_sharp
using System; using System.Linq.Expressions; namespace Bench { public class Program { /// <summary>
/// Compiles a BinaryExpression that multiplies two int parameters /// using Expression.Multiply, wraps it in Expression.Lambda, and /// invokes Compile() to produce a Func&lt;int,int,int&gt; delegate. /// The ParameterExpressions are created via Expression.Parameter. /// </summa...
public static Func<int,int,int> BuildMultiplier() { var a = Expression.Parameter(typeof(int), "a"); var b = Expression.Parameter(typeof(int), "b"); var mul = Expression.Multiply(a, b); var lambda = Expression.Lambda<Func<int,int,int>>(mul, a, b); ...
var fn2 = Program.BuildMultiplier(); if (!(fn2(1, 1) == 1)) throw new Exception("1*1"); if (!(fn2(-3, -4) == 12)) throw new Exception("-3*-4"); // Doc precision checks var method = typeof(Program).GetMethod("BuildMultiplier"); // We check the XML ...
api_usage
42
devbench-api-usage
c_sharp
using System; using System.Text.Json; using System.Text.Json.Nodes; namespace Bench { public class Program { static void Main() { string json = @"{""items"":[{""name"":""A"",""qty"":1},{""name"":""B"",""qty"":2}],""total"":3}"; JsonNode root = JsonNode.Parse(json)!; ...
var items = root["items"]!.AsArray(); var newItem = new JsonObject { ["name"] = "C", ["qty"] = 5 }; items.Add(newItem); int newTotal = 0; foreach (var item in items) { newTotal...
string result = root.ToJsonString(); if (!(root["total"]!.GetValue<int>() == 8)) throw new Exception("total should be 8"); if (!(root["items"]!.AsArray().Count == 3)) throw new Exception("should have 3 items"); var last = root["items"]![2]!; if (!(last["name"...
// Verify JSON roundtrip preserves structure var reparsed = JsonNode.Parse(root.ToJsonString())!; if (!(reparsed["items"]!.AsArray().Count == 3)) throw new Exception("reparse count"); if (!(reparsed["total"]!.GetValue<int>() == 8)) throw new Exception("reparse total"); ...
api_usage
43
devbench-api-usage
c_sharp
using System; namespace Bench { public class Program { static void Main() { int[] data = { 10, 20, 30, 40, 50, 60, 70, 80 }; // Use Index (^) and Range (..) operators to extract slices
int last = data[^1]; int secondLast = data[^2]; int[] middle = data[2..6]; int[] lastThree = data[^3..]; int[] firstTwo = data[..2]; int[] reversed = data[^4..^1];
if (!(last == 80)) throw new Exception("last"); if (!(secondLast == 70)) throw new Exception("secondLast"); if (!(middle.Length == 4 && middle[0] == 30 && middle[3] == 60)) throw new Exception("middle"); if (!(lastThree.Length == 3 && lastThree[0] == 60)) throw new Excep...
// Additional edge cases with Index/Range int first = data[^8]; if (!(first == 10)) throw new Exception("^8 should be first"); int[] all = data[..]; if (!(all.Length == 8)) throw new Exception("full range"); int[] empty = data[3..3]; if...
api_usage
44
devbench-api-usage
c_sharp
using System; using System.Threading.Channels; using System.Threading.Tasks; namespace Bench { public class Program { /// <summary>
/// Creates a bounded Channel&lt;int&gt; with capacity 2 using /// Channel.CreateBounded with BoundedChannelFullMode.Wait. /// The producer calls WriteAsync to enqueue values, blocking when /// the channel is full. The consumer calls ReadAsync in a loop /// until TryRead returns ...
public static async Task<int> ProduceConsumeAsync(int[] values) { var ch = Channel.CreateBounded<int>(new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.Wait }); var producer = Task.Run(async () => { ...
int r2 = await ProduceConsumeAsync(new[] { 10, 20, 30 }); if (!(r2 == 60)) throw new Exception("10+20+30"); int r3 = await ProduceConsumeAsync(new[] { -1, 1 }); if (!(r3 == 0)) throw new Exception("-1+1"); int r4 = await ProduceConsumeAsync(new[] { 100 }); ...
api_usage
45
devbench-api-usage
c_sharp
using System; using System.Collections.Generic; using System.Dynamic; namespace Bench { public class TrackedObject : DynamicObject { private Dictionary<string, object> _store = new(); private List<string> _accessLog = new(); public List<string> AccessLog => _accessLog;
public override bool TrySetMember(SetMemberBinder binder, object? value) { _store[binder.Name] = value!; _accessLog.Add("set:" + binder.Name); return true; } public override bool TryGetMember(GetMemberBinder binder, out object? result) { ...
} public class Program { static void Main() { dynamic obj = new TrackedObject(); obj.Name = "Alice"; obj.Age = 30; string name = obj.Name; int age = obj.Age; var log = ((TrackedObject)obj).AccessLog; if (!(...
// Additional: set same property twice, get nonexistent dynamic obj2 = new TrackedObject(); obj2.X = 1; obj2.X = 2; int x = obj2.X; var log2 = ((TrackedObject)obj2).AccessLog; if (!(log2.Count == 3)) throw new Exception("log2 count"); ...
api_usage
46
devbench-api-usage
c_sharp
using System; namespace Bench { public class Program { static int SumSpan(ReadOnlySpan<int> span) { int s = 0; foreach (var v in span) s += v; return s; } static void Main() { Span<int> buf = stackalloc int[6]; ...
int total = SumSpan(buf); int firstHalf = SumSpan(buf[..3]); int lastHalf = SumSpan(buf[3..]); int mid = SumSpan(buf[1..5]); int lastTwo = SumSpan(buf[^2..]);
if (!(total == 210)) throw new Exception($"total={total}"); if (!(firstHalf == 60)) throw new Exception($"firstHalf={firstHalf}"); if (!(lastHalf == 150)) throw new Exception($"lastHalf={lastHalf}"); if (!(mid == 140)) throw new Exception($"mid={mid}"); if (!...
// Edge slices int single = SumSpan(buf[2..3]); if (!(single == 30)) throw new Exception("single slice"); int empty = SumSpan(buf[3..3]); if (!(empty == 0)) throw new Exception("empty slice"); int fromEnd = SumSpan(buf[^6..^3]); if (!(f...
api_usage
47
devbench-api-usage
c_sharp
using System; using System.Globalization; namespace Bench { public class Program { /// <summary>
/// Formats a decimal as currency using a custom NumberFormatInfo /// where CurrencySymbol is "XYZ", CurrencyGroupSeparator is an /// underscore, CurrencyDecimalDigits is 3, and CurrencyGroupSizes /// is {2, 3} meaning the rightmost group has 2 digits and all /// subsequent group...
public static string FormatCustomCurrency(decimal amount) { var nfi = new NumberFormatInfo { CurrencySymbol = "XYZ", CurrencyGroupSeparator = "_", CurrencyDecimalDigits = 3, CurrencyGroupSizes = new int[] { 2, 3 } ...
string r4 = Program.FormatCustomCurrency(100000m); if (!(r4 == "XYZ1_000_00.000")) throw new Exception($"100000: {r4}"); string r5 = Program.FormatCustomCurrency(-42.7m); if (!(r5 == "(XYZ42.700)" || r5 == "-XYZ42.700" || r5.Contains("42.700"))) throw new Exception($"-42....
api_usage
48
devbench-api-usage
c_sharp
using System; using System.Linq.Expressions; namespace Bench { public class Program { // Build an expression tree that represents: x => x > 0 ? x * 2 : x * -1 // Must use Expression.Condition, Expression.GreaterThan, // Expression.Multiply, Expression.Constant static Func<int, i...
var zero = Expression.Constant(0); var two = Expression.Constant(2); var negOne = Expression.Constant(-1); var test = Expression.GreaterThan(x, zero); var pos = Expression.Multiply(x, two); var neg = Expression.Multiply(x, negOne); var ...
} static void Main() { var fn = BuildAbsDoubler(); if (!(fn(5) == 10)) throw new Exception("5->10"); if (!(fn(-3) == 3)) throw new Exception("-3->3"); if (!(fn(0) == 0)) throw new Exception("0->0"); if (!(fn(1) == 2)) throw new Excepti...
var fn2 = BuildAbsDoubler(); if (!(fn2(100) == 200)) throw new Exception("100->200"); if (!(fn2(-50) == 50)) throw new Exception("-50->50"); if (!(fn2(int.MaxValue / 2) == int.MaxValue / 2 * 2)) throw new Exception("large"); if (!(fn2(-1000) == 1000)) throw ne...
api_usage
49
devbench-api-usage
c_sharp
using System; using System.IO; namespace Bench { public class Program { // Read lines from a StringReader, number them, write to StringWriter static string NumberLines(string text) { var reader = new StringReader(text); var writer = new StringWriter();
string? line; int num = 1; while ((line = reader.ReadLine()) != null) { writer.WriteLine($"{num}: {line}"); num++; } return writer.ToString().TrimEnd();
} static void Main() { string input = "alpha\nbeta\ngamma"; string result = NumberLines(input); if (!(result == "1: alpha\n2: beta\n3: gamma")) throw new Exception($"got: [{result}]"); string single = NumberLines("only"); if (!(single...
string multi = Program.NumberLines("a\nb\nc\nd\ne"); if (!(multi == "1: a\n2: b\n3: c\n4: d\n5: e")) throw new Exception("multi"); string withSpaces = Program.NumberLines(" x \nhello"); if (!(withSpaces == "1: x \n2: hello")) throw new Exception("spaces");
api_usage
50
devbench-api-usage
c_sharp
using System; using System.Globalization; namespace Bench { public class Program { /// <summary>
/// Parses dates using a custom DateTimeFormatInfo where all four /// month-name arrays (AbbreviatedMonthNames, AbbreviatedMonthGenitiveNames, /// MonthNames, MonthGenitiveNames) are replaced with Romanian-style names /// so that standard English month names no longer parse. DateSeparato...
public static DateTime ParseRomanianDate(string s) { var ci = new CultureInfo("en-US"); var dtfi = ci.DateTimeFormat; dtfi.AbbreviatedMonthNames = new[] { "Ian", "Fev", "Mrt", "Avr", "Mai", "Iun", "Iul", "Avg", "Sep", "Okt",...
var d4 = Program.ParseRomanianDate("31.Iul.2023"); if (!(d4.Month == 7 && d4.Day == 31)) throw new Exception("d4 Jul"); var d5 = Program.ParseRomanianDate("10.Avg.2020"); if (!(d5.Month == 8 && d5.Day == 10)) throw new Exception("d5 Aug"); bool threw = false; ...
api_usage
1
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; class ClaimResult { public string Status; public double Patient; public double Plan; public double DeductibleApplied; public double CoinsuranceApplied; } class Adjudicator { public double Copay = 30.0; public double AnnualDeductible = 500.0; ...
if (ProcessedClaims.Contains(claimId)) return null; if (!AllowedRates.ContainsKey(code) || (RequiresAuth.Contains(code) && !AuthorizedClaims.Contains(claimId))) { ProcessedClaims.Add(claimId); ClaimLedger.Add("DENIED:" + claimId + ":" + code); return new ClaimResult {...
} } class Program { static void Main() { var adj = new Adjudicator(); var r1 = adj.AdjudicateLine("C1", "THERAPY", 400.0, false, 20.0); // allowed=320, remaining=300, copay=30, ded=270, coins=0, pat=300 if (r1.Status != "PAID") throw new Exception("r1 status " + r1.Status); ...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate int ledgerBefore = adj.ClaimLedger.Count; double oopBefore = adj.YtdOop; var dup = adj.AdjudicateLine("C1", "THERAPY", 999.0, false, 0.0); if (dup != null) throw new Exception("dup should be null"); ...
code_purpose_understanding
2
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Lot { public string Id; public string Sku; public int Qty; public int ExpiryDay; public bool Quarantined; } class Warehouse { public List<Lot> Lots = new List<Lot>(); public HashSet<string> ProcessedTickets = new Hash...
if (SavedTickets.ContainsKey(ticketId)) return new List<string>(SavedTickets[ticketId]); if (qty <= 0) throw new ArgumentException("qty"); var eligible = Lots.Where(l => l.Sku == sku && !l.Quarantined && l.Qty > 0 && l.ExpiryDay >= shipDay + MinShelfLifeDays) .OrderBy(...
} } class Program { static void Main() { var wh = new Warehouse(); wh.AddLot("L1", "MED", 5, 10, false); wh.AddLot("L2", "MED", 4, 7, false); wh.AddLot("L3", "MED", 9, 6, true); // quarantined var t1 = wh.AllocateOrder("O1", "MED", 6, 4, false); // FEFO: L2(exp7...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate int auditBefore = wh.AuditLog.Count; var dup = wh.AllocateOrder("O1", "MED", 99, 100, true); if (dup.Count != 2 || dup[0] != "PICK:L2:4") throw new Exception("dup ticket"); if (wh.AuditLog.Count != auditBe...
code_purpose_understanding
3
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; class PharmacyRx { public int RxTotalQty; public int FilledQty; public int DaysSupply; public int LastFillDay = -1; public bool Controlled; public bool ExpeditedUsed; public int InventoryQty; public HashSet<string> ProcessedFillIds = new H...
if (ProcessedFillIds.Contains(fillId)) return "DUPLICATE"; if (FilledQty >= RxTotalQty) return "RX_COMPLETE"; if (requestedQty <= 0) throw new ArgumentException("qty"); if (Controlled && expedited) return "CONTROLLED_EXPEDITE_DENIED"; if (Controlled && requestedQty > 30) return "...
} } class Program { static void Main() { var rx = new PharmacyRx { RxTotalQty=90, DaysSupply=30, Controlled=false, InventoryQty=50 }; string first = rx.Fill("F1", 0, 30, false); if (first != "FILLED") throw new Exception(first); if (rx.FilledQty != 30 || rx.InventoryQty != 20) t...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate int logBefore = rx.FillLog.Count; string dup = rx.Fill("F1", 99, 99, true); if (dup != "DUPLICATE") throw new Exception("dup=" + dup); if (rx.FillLog.Count != logBefore) throw new Exception("dup logged"); ...
code_purpose_understanding
4
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; class PayStub { public double Retirement; public double Tax; public double Health; public double Garnishment; public double Net; } class PayrollEngine { public double RetirementRate = 0.05; public double RetirementCap = 1000.0; public dou...
if (ProcessedRuns.Contains(runId)) return null; if (gross <= 0) throw new ArgumentException("gross"); double capLeft = Math.Max(0, RetirementCap - YtdRetirement); double retirement = R2(Math.Min(R2(gross * RetirementRate), capLeft)); double tax = TaxOn(gross - retirement); ...
} } class Program { static void Main() { var pe = new PayrollEngine(); var p1 = pe.RunPayroll("R1", 2000.0); // Ret=100, taxable=1900, tax=100+180=280, health=200, disp=1420, garn=213, net=1207 if (Math.Abs(p1.Retirement - 100.0) > 0.01) throw new Exception("ret=" + p1.Retiremen...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate int logsBefore = pe.PayrollLog.Count; double ytdBefore = pe.YtdNet; var dup = pe.RunPayroll("R1", 9999.0); if (dup != null) throw new Exception("dup not null"); if (pe.PayrollLog.Count != logsBefor...
code_purpose_understanding
5
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Grant { public string Id; public string Sku; public int Remaining; public int StartDay; public int EndDay; } class DenyRule { public string Sku; public int Units; public int StartDay; public int EndDay; } cla...
if (Tickets.ContainsKey(requestId)) return new List<string>(Tickets[requestId]); if (units <= 0) throw new ArgumentException("units"); var active = Grants.Where(g => g.Sku == sku && g.Remaining > 0 && g.StartDay <= day && day <= g.EndDay) .OrderBy(g => g.EndDay).ThenBy(...
} } class Program { static void Main() { var ledger = new EntitlementLedger(); ledger.Grants.Add(new Grant { Id="G1", Sku="API", Remaining=5, StartDay=0, EndDay=10 }); ledger.Grants.Add(new Grant { Id="G2", Sku="API", Remaining=10, StartDay=0, EndDay=20 }); ledger.Denies.Add(new...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate int auditBefore = ledger.AuditLog.Count; var dup = ledger.Consume("R1", "API", 99, 6); if (dup.Count != 1 || dup[0] != "USE:G1:4") throw new Exception("dup"); if (ledger.AuditLog.Count != auditBefore) thro...
code_purpose_understanding
6
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; using System.Linq; class CreditBlock { public string Id; public double Remaining; public int GrantedDay; } class InvoiceLine { public string Description; public double Amount; } class BillingAccount { public double MinimumCommit = 500.0; pub...
if (ClosedPeriods.Contains(periodId)) return null; double usageCharge = R2(units * PerUnitRate); double invoiceAmt = Math.Max(usageCharge, MinimumCommit); var lines = new List<InvoiceLine>(); if (usageCharge < MinimumCommit) lines.Add(new InvoiceLine { Description="MI...
} } class Program { static void Main() { var acct = new BillingAccount(); acct.Credits.Add(new CreditBlock { Id="CR1", Remaining=100.0, GrantedDay=1 }); acct.Credits.Add(new CreditBlock { Id="CR2", Remaining=200.0, GrantedDay=5 }); var inv = acct.ClosePeriod("P1", 8000); ...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate var dup = acct.ClosePeriod("P1", 99999); if (dup != null) throw new Exception("dup not null"); // Minimum commit kicks in acct.Credits.Add(new CreditBlock { Id="CR3", Remaining=50.0, GrantedDay=10 }); ...
code_purpose_understanding
7
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; class DrawResult { public string Status; public double Released; public double Retainage; public double DefectReserve; } class EscrowAccount { public double TotalContract = 100000.0; public double RetainageRate = 0.10; public double DefectRes...
if (ProcessedDraws.Contains(drawId)) return null; if (FinalAccepted) return new DrawResult { Status="ALREADY_CLOSED" }; if (!CompletedMilestones.Contains(milestone)) return new DrawResult { Status="MILESTONE_INCOMPLETE" }; double maxDraw = R2(Math.Min(TotalContract - TotalDrawn, FundBala...
} } class Program { static void Main() { var esc = new EscrowAccount(); esc.FundBalance = 100000.0; esc.CompletedMilestones.Add(1); esc.CompletedMilestones.Add(2); var d1 = esc.ProcessDraw("D1", 1, 20000.0); // retainage=2000, defect=1000, released=17000 ...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate int logBefore = esc.DrawLog.Count; var dup = esc.ProcessDraw("D1", 1, 99999.0); if (dup != null) throw new Exception("dup not null"); if (esc.DrawLog.Count != logBefore) throw new Exception("dup logged"); ...
code_purpose_understanding
8
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; class PaymentResult { public string Status; public double ToFees; public double ToInterest; public double ToPrincipal; public double ToEscrow; public double ToSuspense; } class LoanAccount { public double PrincipalBalance; public double I...
if (ProcessedPayments.Contains(paymentId)) return new PaymentResult { Status="DUPLICATE" }; ProcessedPayments.Add(paymentId); if (Status == "CHARGED_OFF") { SuspenseBalance = R2(SuspenseBalance + amount); PaymentLedger.Add("PAY:" + paymentId + ":RECOVERY:" + a...
} } class Program { static void Main() { var loan = new LoanAccount { PrincipalBalance=10000.0, InterestDue=200.0, EscrowDue=100.0, LateFeePending=true }; var r1 = loan.ApplyPayment("P1", 500.0); // Late fee injected: fees=75. Waterfall: 75+200+100+125=500. principal=9875. if (r...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate int ledgerBefore = loan.PaymentLedger.Count; var dup = loan.ApplyPayment("P1", 9999.0); if (dup.Status != "DUPLICATE") throw new Exception("dup status"); if (loan.PaymentLedger.Count != ledgerBefore) throw...
code_purpose_understanding
9
devbench-code-purpose-understanding
c_sharp
using System; using System.Collections.Generic; class SubResult { public string PrevState; public string NewState; public double Charge; public string Message; } class Subscription { public string State = "TRIAL"; // TRIAL, ACTIVE, PAUSED, GRACE, CANCELLED public int TrialEndDay; public i...
if (ProcessedActions.Contains(actionId)) return null; ProcessedActions.Add(actionId); string prev = State; double charge = 0; string msg = "OK"; switch (action) { case "activate": if (State != "TRIAL") { msg = "INVALID_STATE"; break; } ...
} } class Program { static void Main() { var sub = new Subscription { TrialEndDay=14 }; var a1 = sub.ProcessAction("A1", "activate", 14); if (a1.NewState != "ACTIVE" || Math.Abs(a1.Charge - 50.0) > 0.01) throw new Exception("activate " + a1.NewState + " " + a1.Charge); if (sub.L...
if (visibleOk != 1) throw new Exception("visibleOk"); // Duplicate int logBefore = sub.ActionLog.Count; var dup = sub.ProcessAction("A1", "activate", 99); if (dup != null) throw new Exception("dup not null"); if (sub.ActionLog.Count != logBefore) throw new Exception("dup ...
code_purpose_understanding
End of preview. Expand in Data Studio

DevBench

This dataset packages the DevBench code-completion benchmark published by Microsoft, reformatted into a single data.jsonl file with a category field identifying the task category of each record.

Source

  • Official repository: microsoft/devbench (benchmark/ folder)
  • Retrieved: 2026-09-17, from the main branch of the repository (shallow clone).

Paper

Kumarappan, A., Golnari, P. A., Wen, W., Liu, X., Ryan, G., Sun, Y., Fu, S., & Nallipogu, E. (2026). DevBench: A Realistic, Developer-Informed Benchmark for Code Generation Models. arXiv:2601.11895. https://arxiv.org/abs/2601.11895

@misc{devbench2026,
  author        = {Kumarappan, Adarsh and Golnari, Pareesa Ameneh and Wen, Wen and Liu, Xiaoyu and Ryan, Gabriel and Sun, Yuting and Fu, Shengyu and Nallipogu, Elsie},
  title         = {{DevBench}: A Realistic, Developer-Informed Benchmark for Code Generation Models},
  year          = {2026},
  eprint        = {2601.11895},
  archivePrefix = {arXiv},
  primaryClass  = {cs.LG},
  url           = {https://arxiv.org/abs/2601.11895}
}

License

MIT License — Copyright (c) Microsoft Corporation, as stated in the LICENSE file of the source repository. Redistribute in accordance with the MIT License terms (retain the copyright notice).

File

  • data.jsonl — 1,800 records, one JSON object per line, UTF-8, each with language and category fields.

Structure

DevBench is organized as benchmark/{language}/{category}/{category}.jsonl, i.e. 6 programming languages × 6 task categories × 50 tasks = 1,800 tasks. All 36 source shards were concatenated, each record tagged with:

  • category — the task category, taken from the shard's parent directory name: api_usage, code2NL_NL2code, code_purpose_understanding, low_context, pattern_matching, syntax_completion (50 records each × 6 languages = 300 records per category).
  • language — already present on every source record (python, javascript, typescript, java, cpp, c_sharp); kept as-is (re-added defensively only if a record were ever missing it, which did not occur here).

Each record also retains its original fields: id, testsource, prefix (code visible to the model before the cursor), golden_completion (reference answer), suffix (code visible after the cursor), and assertions (hidden unit-test-style checks used to grade a completion, not shown to the model under evaluation).

category Records Description
api_usage 300 Completions exercising a specific library/API call
code2NL_NL2code 300 Code↔natural-language translation tasks
code_purpose_understanding 300 Completions requiring understanding of surrounding code intent
low_context 300 Completions with minimal surrounding context
pattern_matching 300 Completions following a repeated code pattern
syntax_completion 300 Syntax-level fill-in-the-middle completions
Total 1,800

Known issues / decisions made while preparing this package

  1. Only the benchmark/ folder (the actual task set) was packaged, per the task scope. The repository also ships completions/ (pre-generated model outputs from 9 models), judge_completions/ (LLM-judge scores), prompts/, evaluation/, and analysis/ — these are evaluation artifacts/tooling, not the benchmark data itself, and were left out of data.jsonl.
  2. Each shard's companion *_formatted.txt file (a human-readable rendering of the same JSONL data, used for manual inspection) was skipped as redundant with the .jsonl source.
  3. Record counts were verified as exactly 50 per shard × 36 shards = 1,800 before and after processing; no records were dropped or deduplicated.
  4. Serialized with PowerShell's ConvertTo-Json (no Python available in the preparation environment); non-ASCII characters, if any, are escaped as \uXXXX, which is valid JSON and was validated line-by-line.
Downloads last month
63

Paper for IDENER/devbench