Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    ArrowInvalid
Message:      JSON parse error: The document is empty.
Traceback:    Traceback (most recent call last):
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 354, in _generate_tables
                  df = pandas_read_json(f)
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 38, in pandas_read_json
                  return pd.read_json(path_or_buf, **kwargs)
                         ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 815, in read_json
                  return json_reader.read()
                         ~~~~~~~~~~~~~~~~^^
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 1014, in read
                  obj = self._get_object_parser(self.data)
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 1040, in _get_object_parser
                  obj = FrameParser(json, **kwargs).parse()
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 1176, in parse
                  self._parse()
                  ~~~~~~~~~~~^^
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 1392, in _parse
                  ujson_loads(json, precise_float=self.precise_float), dtype=None
                  ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
              ValueError: Trailing data
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1835, in _prepare_split_single
                  for key, table in generator:
                                    ^^^^^^^^^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 621, in wrapped
                  for item in generator(*args, **kwargs):
                              ~~~~~~~~~^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 357, in _generate_tables
                  raise e
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 295, in _generate_tables
                  pa_table = paj.read_json(
                      io.BytesIO(batch), read_options=paj.ReadOptions(block_size=block_size)
                  )
                File "pyarrow/_json.pyx", line 364, in pyarrow._json.read_json
                File "pyarrow/error.pxi", line 155, in pyarrow.lib.pyarrow_internal_check_status
                File "pyarrow/error.pxi", line 92, in pyarrow.lib.check_status
                  raise convert_status(status)
              pyarrow.lib.ArrowInvalid: JSON parse error: The document is empty.
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1379, in compute_config_parquet_and_info_response
                  parquet_operations, partial, estimated_dataset_info = stream_convert_to_parquet(
                                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~^
                      builder, max_dataset_size_bytes=max_dataset_size_bytes
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  )
                  ^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 956, in stream_convert_to_parquet
                  builder._prepare_split(split_generator=splits_generators[split], file_format="parquet")
                  ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1702, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                                               ~~~~~~~~~~~~~~~~~~~~~~~~~~^
                      gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  ):
                  ^
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1887, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

question
string
answer
string
How do you write a Hello World program in Java?
A minimal Java program defines a class with a main method: public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } The JVM looks for the signature public static void main(String[]). Compile with javac Main.java and run with java Main.
How do you write a Hello World program in C#?
A minimal C# program uses the top-level statements feature (C# 9+) or a class with Main: Console.WriteLine("Hello, World!"); // Or classic form: class Program { static void Main() { Console.WriteLine("Hello, World!"); } } Compile with dotnet build and run with dotnet run.
What is the difference between .NET Framework and .NET (Core)?
.NET Framework is the legacy Windows-only runtime, up to version 4.8. Modern .NET (formerly .NET Core) is cross-platform, open-source, and actively developed (versions 6, 7, 8, 9). Modern .NET supports side-by-side versions, better performance, containers, and Linux/macOS. New projects should target modern .NET.
What are value types and reference types in C#?
Value types (structs, enums, primitives) store data directly and are copied on assignment. Reference types (classes, arrays, strings) store a reference to heap data, so assignments copy the reference. Value types live on the stack or inline; reference types live on the managed heap. 'string' is a reference type but beh...
What is the difference between struct and class in C#?
A struct is a value type, allocated inline or on the stack, copied on assignment, cannot inherit, and is good for small immutable data. A class is a reference type on the heap, supports inheritance, and is good for complex behavior. Structs should be small (typically under 16-24 bytes) and immutable to avoid copy costs...
What is the difference between == and Equals() in C#?
For value types, == compares values. For reference types, == compares references by default unless overloaded, while Equals() can be overridden for logical equality: var a = new string('h', 1); var b = "h"; Console.WriteLine(a == b); // true (string overloads ==) Console.WriteLine(a.Equals(b)); // true For custo...
What is the difference between string and StringBuilder in C#?
string is immutable, so concatenation creates new strings. StringBuilder is mutable and efficient for repeated modifications: var sb = new StringBuilder(); for (int i = 0; i < 1000; i++) sb.Append(i); string result = sb.ToString(); Use StringBuilder in loops and string for stable values. Modern compilers optimize simpl...
What is string interpolation in C#?
String interpolation embeds expressions in a string using $"...": string name = "Alice"; int age = 30; Console.WriteLine($"{name} is {age} years old"); You can format values inline, e.g. $"{age:D3}" for zero-padded, and use raw string literals (C# 11) with triple quotes for multi-line text.
What is a nullable value type in C#?
Nullable<T> or T? allows a value type to hold null: int? x = null; if (x.HasValue) Console.WriteLine(x.Value); Console.WriteLine(x ?? 0); It is useful for optional database columns and missing values. Nullable reference types (C# 8+) add compiler flow analysis to warn about possible null dereferences on reference types...
What are nullable reference types in C#?
With nullable reference types enabled, string means non-null and string? means possibly null: #nullable enable string name = "Alice"; string? maybe = null; Console.WriteLine(maybe?.Length); // safe This shifts null checks to compile time, reducing NullReferenceException. Use the ?. and ?? operators for safe access and...
What is the null-coalescing operator in C#?
?? returns the left operand if non-null, otherwise the right: string name = input ?? "unknown"; string result = a ?? b ?? "default"; ??= assigns only if the left side is null: name ??= "default"; These operators simplify null handling and reduce verbose if checks.
What is the null-conditional operator in C#?
?. short-circuits member access when the object is null, returning null instead of throwing: string? len = person?.Name?.ToUpper(); int? count = list?.Count; You can combine with ?? for defaults: person?.Name ?? "unknown". It works for method calls and indexers (list?[0]).
How do you define a class in C#?
Use the class keyword with fields, properties, constructors, and methods: public class Person { public string Name { get; } public int Age { get; set; } public Person(string name, int age) { Name = name; Age = age; } public string Greet() => $"Hi, I am {Name}"; } Properties with ge...
What is a property in C#?
A property exposes a field through get and set accessors, enabling validation and encapsulation: private int _age; public int Age { get => _age; set { if (value < 0) throw new ArgumentOutOfRangeException(); _age = value; } } Auto-properties, public int Age { get; set; }, are compiler-generat...
What is the difference between a field and a property in C#?
A field is a direct variable on the class. A property is a member with accessors that can add logic, validation, lazy loading, or notifications: public int Count; // field public int Count { get; set; } // property Properties are the public API convention, and they support interfaces, binding, and serializati...
What is an auto-property initializer in C#?
An auto-property can be initialized inline: public string Name { get; set; } = "unknown"; public List<int> Items { get; } = new(); This reduces constructor boilerplate and is evaluated per instance. Read-only collections benefit because the reference cannot be replaced, though the collection remains mutable.
What are init-only properties in C#?
init accessors allow a property to be set during object initialization but not afterward: public class Person { public string Name { get; init; } = ""; } var p = new Person { Name = "Alice" }; // p.Name = "Bob"; // compile error They support immutable object patterns with object initializers and are useful with rec...
What are records in C#?
Records are reference types with value-based equality, concise syntax, and built-in immutability support: public record Person(string Name, int Age); var a = new Person("Alice", 30); var b = a with { Age = 31 }; Records generate constructors, properties, Equals, GetHashCode, and ToString. record struct creates value-ty...
What is a record struct in C#?
A record struct is a value type with record features such as value equality and concise syntax: public record struct Point(int X, int Y); var p = new Point(1, 2); var q = p with { X = 3 }; Unlike record classes, record structs are value types. Use 'readonly record struct' for immutability and to prevent defensive copie...
What are primary constructors in C#?
Primary constructors (C# 12) declare parameters in the type declaration: public class Person(string name, int age) { public string Name { get; } = name; public int Age { get; } = age; } They reduce boilerplate, are captured as needed by members, and are also available for structs and records.
What is inheritance in C#?
Inheritance lets a class derive from a base class to reuse and specialize behavior: class Animal { public virtual void Speak() => Console.WriteLine("..."); } class Dog : Animal { public override void Speak() => Console.WriteLine("Woof"); } C# supports single class inheritance but multiple interface implementati...
What is the difference between override and new in C#?
override replaces a virtual or abstract base member and participates in polymorphism. new hides a base member, and calls through a base reference still use the base implementation: class Base { public virtual void F() {} } class A : Base { public override void F() {} } class B : Base { public new void F() {} } Prefer o...
What is a virtual method in C#?
A virtual method can be overridden by derived classes: public virtual void Speak() { } Calls through a base reference dispatch to the most derived override at runtime. abstract methods are implicitly virtual but must be overridden, and sealed override stops further overriding.
What is the difference between abstract class and interface in C#?
An abstract class can hold state, constructors, and mixed abstract/concrete members, and a class can extend only one. An interface defines a contract and a class can implement many; interfaces can have default implementations (C# 8+) and static members (C# 11). Use abstract classes for shared implementation and interfa...
What are default interface methods in C#?
Default interface methods (C# 8+) provide a body in an interface: interface IGreeter { string Greet(string name) => $"Hello, {name}"; } Implementers can use or override the default. This enables interface evolution without breaking existing implementations, though it requires runtime support and explicit interface ...
What is a sealed class in C#?
A sealed class cannot be inherited: public sealed class Config { } Sealing prevents extension, can enable optimizations, and documents intent. Sealed members prevent further overriding, and 'sealed override' stops a derived override.
What is a static class in C#?
A static class cannot be instantiated and can contain only static members: public static class MathUtil { public static int Square(int x) => x * x; } Static classes are useful for stateless utility methods and extension method containers. They cannot inherit or implement interfaces (except static abstract members s...
What is an extension method in C#?
An extension method adds methods to existing types without modifying them: public static class StringExtensions { public static bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s); } "hello".IsNullOrEmpty(); Extension methods must be in a static class, take 'this' as the first parameter, and are resolved a...
What is a partial class in C#?
A partial class splits a class definition across multiple files: public partial class Form1 { // part 1 } // File2.cs public partial class Form1 { // part 2 } The compiler merges them. Partial classes are common with generated code (designers, source generators) and source generators, and partial methods allow ...
What is an enum in C#?
An enum defines a set of named constants: public enum Status { Active, Inactive, Pending } By default, values are int starting at 0. Enums can have explicit values, underlying types (byte, long), and the [Flags] attribute for bitmask combinations: [Flags] enum Permissions { None = 0, Read = 1, Write = 2 }
What is the difference between const and readonly in C#?
const is a compile-time constant, implicitly static, and can only hold primitives, strings, and enums. readonly is set at declaration or in a constructor, can hold any type, and is evaluated at runtime: public const int Max = 100; public readonly DateTime Created = DateTime.Now; Use const for true constants and readonl...
What is a generic type in C#?
Generics enable type-safe reusable code without boxing or casts: public class Box<T> { public T Value { get; set; } } var b = new Box<int> { Value = 42 }; Generics are reified at runtime, so typeof(List<int>) differs from typeof(List<string>), unlike Java erasure. Constraints such as where T : class refine allowed ...
What are generic constraints in C#?
Constraints restrict the types that can be used with a generic parameter: public T Create<T>() where T : new() => new T(); Common constraints: class, struct, new(), base class, interface, notnull, and unmanaged. They enable the compiler to allow operations on T and improve type safety. Multiple constraints combine with...
What is the difference between List<T> and T[] in C#?
T[] is a fixed-size array with O(1) indexed access and no resizing. List<T> wraps a resizable array with amortized O(1) Add, plus methods such as Remove, Sort, and Find. Arrays are slightly faster and lower-overhead, while List is more flexible for dynamic collections.
What is the difference between List<T> and LinkedList<T>?
List<T> is backed by an array with fast indexed access and amortized O(1) append, but O(n) insertion or removal in the middle. LinkedList<T> is a doubly linked list with O(1) insertion or removal at known nodes but O(n) access. List is usually the better default due to cache locality.
What is the difference between Dictionary<TKey, TValue> and SortedDictionary?
Dictionary is a hash table with average O(1) lookup and no ordering. SortedDictionary is a balanced tree with O(log n) operations and keys kept in sorted order. Use Dictionary for fast lookups, and SortedDictionary or SortedList when ordered iteration matters.
What is the difference between HashSet<T> and SortedSet<T>?
HashSet is a hash-based set with average O(1) operations and no ordering. SortedSet is a tree-based set with O(log n) operations and elements in sorted order. Both enforce uniqueness; choose based on ordering needs and performance profile.
What is a ConcurrentDictionary in C#?
ConcurrentDictionary is a thread-safe hash map designed for high concurrency. It uses fine-grained locking and lock-free reads: var cache = new ConcurrentDictionary<string, int>(); cache.AddOrUpdate("a", 1, (k, v) => v + 1); cache.TryGetValue("a", out var value); Operations such as AddOrUpdate, GetOrAdd, and TryRemove ...
What is an IEnumerable<T>?
IEnumerable<T> represents a sequence that can be iterated with foreach. It exposes GetEnumerator() and supports lazy evaluation: IEnumerable<int> GetNumbers() { yield return 1; yield return 2; } LINQ operators return IEnumerable and compose lazily until enumerated. Use ToList or ToArray to materialize results.
What is the difference between IEnumerable and IQueryable?
IEnumerable executes in memory and is suitable for LINQ to Objects. IQueryable builds expression trees that a provider such as Entity Framework translates into queries (SQL): IQueryable<User> q = db.Users.Where(u => u.Age > 18); IEnumerable<User> list = q.ToList(); Keep filtering on IQueryable to push work to the datab...
What is LINQ?
LINQ, Language Integrated Query, provides a uniform query syntax over collections, databases, XML, and more: var adults = people.Where(p => p.Age >= 18) .OrderBy(p => p.Name) .Select(p => p.Name) .ToList(); It supports query syntax (from x in ... where ... select...
What is the difference between Select and SelectMany in LINQ?
Select projects each element one-to-one. SelectMany projects each element to a sequence and flattens the results: var flat = people.SelectMany(p => p.Phones).ToList(); Use SelectMany when each input yields zero or more outputs, such as flattening nested collections.
What is deferred execution in LINQ?
LINQ queries are not executed when defined; they run when enumerated: var q = list.Where(x => x > 0); // no work yet foreach (var x in q) { } // executes This enables composition but can surprise you if the source changes or if the query runs multiple times. Materialize with ToList or ToArray when you need a s...
What is the difference between First, FirstOrDefault, Single, and SingleOrDefault?
First returns the first match and throws if none; FirstOrDefault returns default(T) instead. Single requires exactly one match and throws on zero or many; SingleOrDefault returns default on zero but throws on many. Choose based on whether zero, one, or many matches are valid.
What is the difference between Any() and Count() > 0 in LINQ?
Any() stops at the first element and is O(1) for many sources, while Count() enumerates the entire sequence. Prefer Any() when you only need to know whether the sequence is non-empty: if (items.Any()) { } For IQueryable, Any() translates to an efficient EXISTS query, while Count() may scan more rows.
How do you group data in LINQ?
Use GroupBy to group elements by a key: var groups = people.GroupBy(p => p.Department); foreach (var g in groups) { Console.WriteLine($"{g.Key}: {g.Count()}"); } Each group is an IGrouping<TKey, TElement>, and you can project aggregates with Select, such as average salary per department.
How do you join two sequences in LINQ?
Use Join for inner joins and GroupJoin for grouped results: var result = from u in users join o in orders on u.Id equals o.UserId select new { u.Name, o.Total }; Method syntax uses users.Join(orders, u => u.Id, o => o.UserId, (u, o) => new { u.Name, o.Total }). Left joins require DefaultIfEmpt...
What is the difference between IEnumerable and ICollection?
IEnumerable supports forward iteration only. ICollection extends it with Count, Add, Remove, Contains, and CopyTo, representing a mutable collection. IList and IDictionary add indexed or keyed access. Expose the narrowest interface that callers need.
What is an async method in C#?
An async method can await asynchronous operations without blocking the calling thread: public async Task<string> FetchAsync() { using var client = new HttpClient(); return await client.GetStringAsync("https://example.com"); } The async modifier enables await, and the method returns Task, Task<T>, or ValueTask. ...
What is the difference between Task and Thread in C#?
Thread is an OS-level thread with manual management and high cost. Task is a higher-level abstraction scheduled on the thread pool, supporting continuations, cancellation, and composition via async/await. Prefer Task and async/await for concurrency, and reserve Thread for specialized scenarios.
What is the difference between Task and ValueTask?
Task is a reference type representing an asynchronous operation, allocated on the heap. ValueTask is a struct that avoids allocation when the result is often synchronous or cached, but it must be awaited only once and not used concurrently. Use ValueTask in hot paths where allocation matters.
What does await actually do?
await suspends the async method until the awaited task completes, freeing the thread to do other work. When the task completes, execution resumes on a captured synchronization context or the thread pool. The compiler generates a state machine that preserves locals across awaits.
What is ConfigureAwait(false) and when should you use it?
ConfigureAwait(false) tells the runtime not to marshal continuation back to the captured synchronization context: await SomeAsync().ConfigureAwait(false); Use it in library code to avoid deadlocks and context overhead. In UI or ASP.NET Classic code that needs the context after the await, keep the default.
What is a deadlock in async code and how do you avoid it?
A common async deadlock occurs when blocking on .Result or .Wait() while the synchronization context is captured and cannot run the continuation. Avoid blocking on async code; use await end to end. In libraries, use ConfigureAwait(false), and in UI code, keep the context where needed.
What is CancellationToken in C#?
CancellationToken propagates cancellation cooperatively: public async Task WorkAsync(CancellationToken ct) { await Task.Delay(1000, ct); ct.ThrowIfCancellationRequested(); } Create tokens with CancellationTokenSource, which can Cancel after a timeout. Async APIs commonly accept a token as their last parameter.
What is the difference between Task.Run and async/await?
Task.Run offloads CPU-bound work to the thread pool. async/await does not create threads by itself; it frees the current thread while awaiting I/O. Use Task.Run for CPU-bound work in UI apps, and use async I/O APIs for network and file operations instead of wrapping them in Task.Run.
What is a lock statement in C#?
lock provides mutual exclusion for a critical section: private readonly object _gate = new(); public void Increment() { lock (_gate) { _count++; } } The lock is released automatically on exit or exception. Lock on a private reference object, avoid locking on 'this' or strings, and keep the critical sect...
What is the difference between lock, Monitor, and Mutex?
lock is syntactic sugar for Monitor.Enter/Exit and works within a process. Monitor adds TryEnter with timeouts and Wait/Pulse. Mutex can synchronize across processes but is slower and OS-level. Use lock by default, Monitor for advanced in-process needs, and Mutex for cross-process coordination.
What are Interlocked operations in C#?
Interlocked provides atomic operations on variables without locks: Interlocked.Increment(ref _counter); Interlocked.CompareExchange(ref _value, newValue, comparand); They are fast and lock-free, suitable for counters and simple state transitions, but they do not protect multi-variable invariants.
What is a SemaphoreSlim in C#?
SemaphoreSlim limits concurrent access to a resource: private static readonly SemaphoreSlim _sem = new(3); await _sem.WaitAsync(); try { /* work */ } finally { _sem.Release(); } Unlike Semaphore, it is lightweight and supports async waits, making it ideal for throttling asynchronous operations.
What is the difference between parallel and async concurrency in C#?
Parallelism runs CPU-bound work simultaneously on multiple cores, using Parallel.For or PLINQ. Async concurrency overlaps I/O-bound work without blocking threads, using async/await. They solve different problems and can be combined carefully, but async should not be used for CPU-bound work.
How do you use Parallel.For in C#?
Parallel.For executes a loop body in parallel across cores: Parallel.For(0, 100, i => { Process(i); }); It partitions work and handles scheduling. Keep iterations independent, avoid shared mutable state, and prefer Parallel.ForEachAsync for async bodies.
What is a thread-safe collection in C#?
The System.Collections.Concurrent namespace provides thread-safe collections: ConcurrentDictionary, ConcurrentQueue, ConcurrentStack, ConcurrentBag, and BlockingCollection. They use lock-free or fine-grained locking techniques for high concurrency, avoiding manual locking around shared collections.
What is a BlockingCollection in C#?
BlockingCollection supports producer-consumer patterns with blocking and bounding: var q = new BlockingCollection<int>(100); q.Add(1); // blocks if full int x = q.Take(); // blocks if empty q.CompleteAdding(); It wraps a concurrent collection and simplifies coordination without explicit wait/notify.
What is garbage collection in C#?
The .NET GC automatically reclaims managed heap memory for unreachable objects. It is generational (gen 0, 1, 2) and uses mark-and-sweep with compaction. Large objects go to the Large Object Heap. Finalizers and IDisposable handle unmanaged resources, but finalizers are non-deterministic and should be avoided when poss...
What is the difference between managed and unmanaged resources?
Managed resources are handled by the GC, such as .NET objects. Unmanaged resources include file handles, sockets, and native memory, which the GC cannot reclaim. Wrap them in IDisposable and release them deterministically with using or Dispose, optionally adding a finalizer as a safety net.
What is the IDisposable pattern in C#?
IDisposable provides a Dispose method for deterministic cleanup: public class Resource : IDisposable { private bool _disposed; public void Dispose() { if (_disposed) return; // release resources _disposed = true; } } using var r = new Resource(); The using statement or declaration ca...
What is the difference between using statement and using declaration?
A using statement scopes disposal to a block: using (var f = File.OpenRead("a")) { /* use f */ } A using declaration disposes at the end of the enclosing scope (C# 8+): using var f = File.OpenRead("a"); // disposed at end of method Both call Dispose, and the declaration form reduces nesting.
What is a finalizer in C#?
A finalizer (~ClassName) runs before the GC reclaims an object, providing a last chance to release unmanaged resources: ~Resource() { /* cleanup */ } Finalizers are non-deterministic, delay collection, and should be used only when the class directly owns unmanaged resources, with Dispose suppressing finalization via GC...
What is a WeakReference in C#?
WeakReference allows an object to be collected while still providing access if it is alive: var wr = new WeakReference<CacheEntry>(entry); if (wr.TryGetTarget(out var target)) { /* use */ } It is useful for caches and event handlers where you do not want to keep objects alive. Generic WeakReference<T> is preferred in m...
What is a Span<T> in C#?
Span<T> is a stack-only, non-owning view over contiguous memory, avoiding allocations: Span<int> s = stackalloc int[3]; ReadOnlySpan<char> slice = "hello".AsSpan(1, 3); It works with arrays, stackalloc, and native memory, and is used in high-performance parsing and buffer handling. It cannot be stored on the heap or us...
What is a Memory<T> in C#?
Memory<T> is a heap-friendly counterpart to Span<T>, usable in async methods and as a field: async Task ReadAsync(Memory<byte> buffer) { await stream.ReadAsync(buffer); } It provides a Span property for synchronous access. Use Memory when the buffer must outlive a stack frame or cross await points.
What is the difference between ref, out, and in parameters in C#?
ref passes by reference and requires initialization before the call. out passes by reference and must be assigned inside the method. in passes by reference as read-only: void Inc(ref int x) { x++; } bool TryParse(string s, out int v) { v = 0; return false; } void Print(in Point p) { } Use in for large readonly structs ...
What is the params keyword in C#?
params allows a variable number of arguments: public static int Sum(params int[] numbers) { return numbers.Sum(); } Sum(1, 2, 3); C# 13 adds params collections, and ReadOnlySpan<T> params avoids allocations. The params parameter must be last.
What is an indexer in C#?
An indexer allows objects to be indexed like arrays: public class Matrix { private readonly int[,] _data = new int[3, 3]; public int this[int r, int c] { get => _data[r, c]; set => _data[r, c] = value; } } var m = new Matrix(); m[0, 1] = 5; Indexers use the this keyword and can be overloaded...
What are tuples in C#?
Tuples group values without defining a type: var person = (Name: "Alice", Age: 30); Console.WriteLine(person.Name); var (name, age) = person; ValueTuple is a struct with value equality and deconstruction support. Tuples are convenient for multiple return values but less self-documenting than named types for public APIs...
What is deconstruction in C#?
Deconstruction unpacks a tuple or custom type into variables: var (x, y) = point; var (name, _) = person; For custom types, define a Deconstruct method: public void Deconstruct(out int x, out int y) { x = X; y = Y; } It improves readability for multiple return values.
What is pattern matching in C#?
Pattern matching tests types and shapes concisely: if (obj is string s && s.Length > 0) { } var result = shape switch { Circle c => Math.PI * c.Radius * c.Radius, Rectangle r => r.Width * r.Height, _ => 0 }; Patterns include type, property, relational, logical (and/or/not), and list patterns (C# 11). Switch...
What are switch expressions in C#?
Switch expressions return a value and use concise arm syntax: string label = value switch { < 0 => "negative", 0 => "zero", _ => "positive" }; Arms are evaluated in order, and the compiler checks exhaustiveness for many patterns. They reduce boilerplate compared to switch statements.
What are list patterns in C#?
List patterns (C# 11) match sequences: if (arr is [1, 2, .. var rest]) { } if (arr is [_, _, 3]) { } They combine with property and relational patterns to match array and span shapes, useful in parsing and validation.
What is the with expression in C#?
The with expression creates a copy of a record or struct with some properties changed: var a = new Person("Alice", 30); var b = a with { Age = 31 }; It performs a shallow copy and applies the initializers. with works on records and structs (C# 10+) and supports reference-type members via clone semantics.
What are anonymous types in C#?
An anonymous type is a compiler-generated immutable type for ad-hoc projections: var p = new { Name = "Alice", Age = 30 }; Console.WriteLine(p.Name); They have value equality and are often used in LINQ projections. They cannot be returned from public methods because their type is not nameable.
What is a delegate in C#?
A delegate is a type-safe function pointer: public delegate int MathOp(int a, int b); MathOp add = (a, b) => a + b; Console.WriteLine(add(2, 3)); Delegates underpin events and callbacks. Func<...>, Action<...>, and Predicate<T> cover most needs without custom declarations.
What is the difference between Func, Action, and Predicate?
Func<T, TResult> returns a value, Action<T> returns void, and Predicate<T> returns bool: Func<int, int> square = x => x * x; Action<string> log = s => Console.WriteLine(s); Predicate<int> isEven = x => x % 2 == 0; They are built-in delegates that reduce the need for custom delegate types.
What is an event in C#?
An event is a delegate-based notification mechanism: public event EventHandler? Changed; protected void OnChanged() => Changed?.Invoke(this, EventArgs.Empty); Subscribers use += and -=. Events encapsulate the delegate so only the declaring class can raise them, preventing external invocation.
What is the difference between delegate and event?
A delegate field can be invoked and reassigned by anyone with access. An event exposes only += and -= to subscribers, so only the declaring class can raise it. Events also work with the standard EventHandler pattern and support designer integration in UI frameworks.
What is a lambda expression in C#?
A lambda is an anonymous function: Func<int, int> square = x => x * x; Action<string> print = s => Console.WriteLine(s); Lambdas capture variables from the enclosing scope (closures) and are widely used with LINQ and events. Expression lambdas versus statement lambdas differ in body syntax.
What is a closure in C#?
A closure captures variables from the enclosing scope: int factor = 2; Func<int, int> mul = x => x * factor; The compiler lifts captured variables into a generated class. Captured variables are shared by reference, so loops can capture the same variable unless you copy it inside the loop body.
What is reflection in C#?
Reflection inspects and invokes types and members at runtime: Type t = typeof(Person); var prop = t.GetProperty("Name"); object? value = prop?.GetValue(person); It powers serialization, DI containers, and ORMs. Reflection is slower and not compile-time checked, so cache metadata and prefer source generators for hot pat...
What are attributes in C#?
Attributes attach metadata to code and can be read at runtime: [Obsolete("use NewMethod")] public void OldMethod() { } public class MyAttr : Attribute { } [MyAttr] public class C { } Built-in attributes include [Serializable], [JsonPropertyName], and [HttpGet]. Frameworks use attributes for configuration, validation, a...
What are source generators in C#?
Source generators run during compilation and add source code to the compilation: [Generator] public class MyGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext ctx) { } public void Execute(GeneratorExecutionContext ctx) { } } They generate boilerplate at compile time, improving ...
What is the difference between checked and unchecked arithmetic in C#?
checked arithmetic throws OverflowException on overflow, while unchecked wraps silently: int x = int.MaxValue; checked { x++; } // throws unchecked { x++; } // wraps By default, arithmetic is unchecked unless the compiler option or a checked block enables checking. Use checked for financial or safety-critical calculati...
What is the difference between throw and throw ex in a catch block?
throw; rethrows the current exception and preserves the original stack trace. throw ex; resets the stack trace to the current line, hiding the original origin: try { Work(); } catch (Exception) { throw; } // correct Prefer throw; to preserve diagnostics, and use ExceptionDispatchInfo when rethrowing across contexts.
What is an exception filter in C#?
Exception filters catch an exception only when a condition is true: try { Work(); } catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { // handle 404 } Filters run before the stack unwinds, can inspect state cheaply, and improve readability compared to rethrowing.
What is the difference between Exception and ApplicationException?
Exception is the base class for all exceptions. ApplicationException was intended for user-defined exceptions but is now discouraged; Microsoft recommends deriving custom exceptions directly from Exception. Both are equivalent in behavior, but Exception avoids ambiguity.
How do you create a custom exception in C#?
Derive from Exception and follow the standard constructor pattern: public class ValidationException : Exception { public ValidationException(string message) : base(message) { } public ValidationException(string message, Exception inner) : base(message, inner) { } } Include serialization constructors for compati...
What is the try-catch-finally pattern in C#?
try contains code that may throw, catch handles exceptions, and finally always runs: try { Work(); } catch (IOException ex) { Log(ex); } finally { Cleanup(); } Finally runs even if an exception is thrown or a return occurs, making it suitable for releasing resources not handled by using.
What is a using directive in C#?
A using directive imports namespaces: using System.Text; using static System.Math; // static members using Alias = System.Collections.Generic.List<int>; Global usings (C# 10) apply to the whole project via global using. Using directives reduce verbosity but should be kept tidy to avoid ambiguity.
What is a global using in C#?
A global using applies to all files in a project: global using System; global using System.Linq; It is typically placed in a GlobalUsings.cs file or generated by the SDK, reducing repetitive imports. Aliases and static usings can also be global.
What is a file-scoped namespace in C#?
A file-scoped namespace declares the namespace for the entire file without braces: namespace MyApp.Services; public class UserService { } It reduces indentation and boilerplate compared to block-scoped namespaces, and a file can contain only one file-scoped namespace.
End of preview.
README.md exists but content is empty.
Downloads last month
69