csharp

Exploring the .NET CoreFX Part 16: Platform-Specific Builds Using Compile-Time Polymorphism
Exploring the .NET CoreFX .net core csharp
Published: 2015-03-01
Exploring the .NET CoreFX Part 16: Platform-Specific Builds Using Compile-Time Polymorphism
This is part 16/17 of my Exploring the .NET CoreFX series. While .NET has historically been limited to Windows machines, Mono notwithstanding, the introduction of the cross-platform .NET Core runtime has introduced the possibility of running .NET Core applications on Unix machines. With this possibility, developers may have the need of writing platform-specific code. One way to write platform-specific code is: Define a conceptual base class which will have an identical name and methods across all platforms. Read more...
Exploring the .NET CoreFX Part 15: Using Non-Generic Factory Classes to Enable Type Inference
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2015-02-18
Exploring the .NET CoreFX Part 15: Using Non-Generic Factory Classes to Enable Type Inference
This is part 15/17 of my Exploring the .NET CoreFX series. While C# supports type inference for generic methods, it does not support type inference for constructors. In other words, while this code works: 1 2 3 4 5 6 7 8 9 public class FooFactory { public static Foo<T> Create<T>(T value) { return new Foo<T>(value); } } var myObj = FooFactory.Create(212); This code does not: 1 2 3 4 5 6 7 public class Foo<T> { private readonly T field; public Foo(T value) { field = value; } } var obj = new Foo(212); // DOES NOT WORK For more background on why this is, see this StackOverflow post. Read more...
Exploring the .NET CoreFX Part 13: ImmutableList is an AVL Tree
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2015-01-13
Exploring the .NET CoreFX Part 13: ImmutableList is an AVL Tree
This is part 13/17 of my Exploring the .NET CoreFX series. Most implementations of IList, including System.Collections.Generic.List, are dynamic arrays. System.Collections.Immutable.ImmutableList is different – it is an AVL tree. This results in significantly different performance characteristics: List ImmutableList Indexing O(1) O(log n) Append O(1) average, O(n) worst-case O(log n) Insert at arbitrary index O(n) O(log n) Remove O(n) O(log n) Memory layout Contiguous for value types Non-contiguous The data structure behind ImmutableList was likely chosen so that modifications to the list are non-destructive and require minimal data copying. Read more...
Exploring the .NET CoreFX Part 12: Aggressive Inlining
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2015-01-05
Exploring the .NET CoreFX Part 12: Aggressive Inlining
This is part 12/17 of my Exploring the .NET CoreFX series. In C++, the inline keyword allows a developer to provide a hint to the compiler that a particular method should be inlined. C# has the identical ability but uses an attribute instead: 1 2 3 4 5 6 7 8 9 10 11 internal class SecurePooledObject<T> { .... [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsOwned<TCaller>(ref TCaller caller) where TCaller : struct, ISecurePooledObjectUser { return caller. Read more...
Exploring the .NET CoreFX Part 11: Code Contracts
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-12-17
Exploring the .NET CoreFX Part 11: Code Contracts
This is part 11/17 of my Exploring the .NET CoreFX series. In 2008, Microsoft Research published Code Contracts, which provide a language-agnostic way to express coding assumptions in .NET programs. The assumptions take the form of pre-conditions, post-conditions, and object invariants. Here is a simple example of code which uses Code Contracts: 1 2 3 4 5 6 7 8 9 10 11 12 using System.Diagnostics.Contracts; public class StringUtils { internal static string Append(string s1, string s2) { Contract. Read more...
Exploring the .NET CoreFX Part 10: Performance Tuning Enumeration
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-12-02
Exploring the .NET CoreFX Part 10: Performance Tuning Enumeration
This is part 10/17 of my Exploring the .NET CoreFX series. The .NET Core’s System.Collections.Immutable.ImmutableArray provides two enumerators. The first has been highly tuned for speed, and the second is a fallback for compatibility when it is required. The high-performance enumerator uses the following performance optimizations: The enumerator is a struct, rather than a class, so that it is stack-allocated rather than heap-allocated. The enumerator does not implement IEnumerator or IEnumerator, as this would require it to implement IDisposable. Read more...
Exploring the .NET CoreFX Part 9: Immutable Collections and the Builder Pattern
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-12-01
Exploring the .NET CoreFX Part 9: Immutable Collections and the Builder Pattern
This is part 9/17 of my Exploring the .NET CoreFX series. Using the builder pattern to allow for easier construction of immutable objects is well-known. The .NET Core’s immutable collections assembly, System.Collections.Immutable, also uses the builder pattern, but for a slightly different reason: to improve the performance of making many changes to the collection. This is possible because, unlike the immutable collection itself, the builder pattern does not need to maintain the immutable collection’s invariants after each modification. Read more...
Exploring the .NET CoreFX Part 8: NullReferenceException Performance Tricks
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-28
Exploring the .NET CoreFX Part 8: NullReferenceException Performance Tricks
This is part 8/17 of my Exploring the .NET CoreFX series. The .NET Core’s System.Collections.Immutable.ImmutableArray class implements an immutable wrapper around a normal C# managed array. This looks something like: 1 2 3 4 5 public struct ImmutableArray<T> { internal T[] array; ... } ImmutableArray.array is lazy-initialized. Within the ImmutableArray class, there are a number of methods which have the precondition that ImmutableArray.array must be initialized. These preconditions must be checked before the method begins processing to make sure we handle invalid states correctly. Read more...
Exploring the .NET CoreFX Part 7: Reference Versus Structural Equality
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-27
Exploring the .NET CoreFX Part 7: Reference Versus Structural Equality
This is part 7/17 of my Exploring the .NET CoreFX series. In the previous post, I referenced EqualityComparer.Default. If T does not implement IEquatable, EqualityComparer.Default will use the framework-defined Object.Equals(), which implements reference equality. However, many times you want to compare two types for structural equality (i.e. identical content) rather than reference equality (i.e. two references point to the same instance of the class). The interface IStructuralEquatable was defined to allow a class to explicitly implement structural, rather than reference equality. Read more...
Exploring the .NET CoreFX Part 6: Use IEquatable for Higher-Performance Equals()
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-24
Exploring the .NET CoreFX Part 6: Use IEquatable for Higher-Performance Equals()
This is part 6/17 of my Exploring the .NET CoreFX series. Let’s say you are writing a custom IList which contains the following code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class MyList<T> : IList<T> { private T[] array; ... public int IndexOf(T item) { for (int i = 0; i != array.Length; ++i) { if (this.array[i].Equals(item)) { return i; } } return -1; } } The above code uses T“s implementation of Object. Read more...
Exploring the .NET CoreFX Part 5: Keep Indexers Trivial to Allow JIT Optimization
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-21
Exploring the .NET CoreFX Part 5: Keep Indexers Trivial to Allow JIT Optimization
This is part 5/17 of my Exploring the .NET CoreFX series. This is a simple recommendation based on observations from System.Collections.Immutable. Recommendations Keep the implementation of an indexer as trivial as possible to allow the JIT optimization of removing array bounds checking to work. For example, don’t check if a member variable is null; just use it and allow the NullReferenceException to happen naturally. In other words, use: 1 2 3 4 5 6 7 public T this[int index] { get { return this. Read more...
Exploring the .NET CoreFX Part 4: The Requires Convenience Class
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-20
Exploring the .NET CoreFX Part 4: The Requires Convenience Class
This is part 4/17 of my Exploring the .NET CoreFX series. The System.Collections.Immutable project in the .NET CoreFX includes a convenience class called Requires, which looks like: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 internal static class Requires { [DebuggerStepThrough] public static T NotNull([ValidatedNotNull]T value, string parameterName) where T : class // ensures value-types aren't passed to a null checking method { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } . Read more...
Exploring the .NET CoreFX Part 3: Making Methods Debugger-Friendly
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-19
Exploring the .NET CoreFX Part 3: Making Methods Debugger-Friendly
This is part 3/17 of my Exploring the .NET CoreFX series. System.Collections.Immutable uses a number of attributes to make it more debugger-friendly. Here are the key attributes: DebuggerStepThrough Occasionally a method is so simple that it doesn’t make sense to have the debugger step into it. The System.Diagnostics.DebuggerStepThroughAttribute instructs the debugger to step through the code instead of stepping into the code. Here is an example from System.Collections.Immutable: 1 2 3 4 5 6 7 8 9 10 11 internal static class Requires { [DebuggerStepThrough] public static void Range(bool condition, string parameterName, string message = null) { if (! Read more...
Exploring the .NET CoreFX Part 2: Cache ThreadLocal Variables in Locals
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-18
Exploring the .NET CoreFX Part 2: Cache ThreadLocal Variables in Locals
This is part 2/17 of my Exploring the .NET CoreFX series. Thread-local storage allows you to mark a global or static variable as local to a thread. In Win32, thread-local storage is provided by the functions TlsAlloc, TlsGetValue, TlsSetValue, and TlsFree. Similarly, C# provides System.ThreadStaticAttribute and System.Threading.ThreadLocal. Unfortunately, thread-local storage comes at a cost. Reading or writing a thread-local variable is far more expensive than reading or writing a local variable. Read more...
Exploring the .NET CoreFX Part 1: Annotate Pure Methods With PureAttribute
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-17
Exploring the .NET CoreFX Part 1: Annotate Pure Methods With PureAttribute
This is part 1/17 of my Exploring the .NET CoreFX series. A pure method is a method that does not make any visible state changes. John Carmack, in his article In-Depth: Functional Programming in C++, notes many advantages of pure functions: Pure functions have a lot of nice properties. Thread safety. A pure function with value parameters is completely thread safe. With reference or pointer parameters, even if they are const, you do need to be aware of the danger that another thread doing non-pure operations might mutate or free the data, but it is still one of the most powerful tools for writing safe multithreaded code. Read more...
Handling Multiple QueryString Parameters With the Same Key in ASP.NET
ASP.NET asp.net csharp
Published: 2009-09-23
Handling Multiple QueryString Parameters With the Same Key in ASP.NET
When you are processing an HTTP request in ASP.NET you can retrieve the user-provided query string parameters using the HttpRequest.QueryString property. This property is an instance of the NameValueCollection class. If the user has provided multiple parameters with the same key in the query string, HttpRequest.QueryString[key] will return all the values concatenated together with commas. If you would rather process the values individually, use HttpRequest.QueryString.GetValues(key), which will return an array of all the provided values. Read more...
XmlTextWriter Can Produce Invalid XML
XML / XPath / XSLT csharp xml
Published: 2007-06-16
XmlTextWriter Can Produce Invalid XML
XmlTextWriter is .NET’s class for writing XML in a forward-only streaming manner. It is highly efficient and is the preferred way to generate XML in .NET in most circumstances. I find XmlTextWriter so useful I wrote a partial C++ implementation of it in Implenting IXmlWriter Series. Unfortunately, XmlTextWriter isn’t quite as strict as it could be. It will let slip some invalid XML such as duplicate attributes, invalid Unicode characters in the range 0×0 to 0×20, and invalid element and attribute names. Read more...
How Return XML From ASPX in ASP.NET 1.1
ASP.NET asp.net csharp xml
Published: 2006-02-06
How Return XML From ASPX in ASP.NET 1.1
I’m not sure if this is the “canonical” way to do it but here’s a description of how to write an ASP.NET 1.1 ASPX page which returns a XML document (e.g. when writing a home-brewed web service). First, create a new Web Form (I will call it WebService.aspx). As we will be progamatically generating the XML in the HTTP response rather than sending the (processed) content of the ASPX file, delete everything from the ASPX file but the @Page directive, so that it looks something like: Read more...
Revisiting Excel Interop
Excel Interop csharp excel interop
Published: 2005-08-24
Revisiting Excel Interop
I ran into problem today relating to Excel interop. A coworker made a change to a C# application I wrote and was trying to build it. The program relied on a project which had a reference to the Microsoft Excel 9.0 Object Library which ships with Office 2000. However, the coworker had Office 2003 installed which includes the Excel 11.0 Object Library and not the Excel 9.0 Object Library. Because of this, he could not build the application. Read more...
Deterministic Finalization and IDisposable Part 5: Useful IDisposable Class 3: AutoReleaseComObject
Deterministic Finalization and IDisposable csharp excel interop
Published: 2005-02-15
Deterministic Finalization and IDisposable Part 5: Useful IDisposable Class 3: AutoReleaseComObject
This is part 5/5 of my Deterministic Finalization and IDisposable post series. This is the final example in my series on deterministic finalization in garbage-collected languages and the true motive behind the series: AutoReleaseComObject. The idea behind AutoReleaseComObject is simple: it is nothing but a wrapper around a COM object which calls Marshal.ReleaseComObject() upon Dispose() until the COM object’s reference count is 0 and the object is freed. Here’s the implementation: Read more...
Deterministic Finalization and IDisposable Part 4: Useful IDisposable Class 2: AutoDeleteFile
Deterministic Finalization and IDisposable csharp
Published: 2005-02-14
Deterministic Finalization and IDisposable Part 4: Useful IDisposable Class 2: AutoDeleteFile
This is part 4/5 of my Deterministic Finalization and IDisposable post series. I guess my definition of tomorrow is much longer than I thought, but here’s another useful IDisposable class which I shall present without comment: AutoDeleteFile. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 using System; using System. Read more...
Deterministic Finalization and IDisposable Part 3: Useful IDisposable Class 1: TimedLock
Deterministic Finalization and IDisposable csharp
Published: 2005-02-13
Deterministic Finalization and IDisposable Part 3: Useful IDisposable Class 1: TimedLock
This is part 3/5 of my Deterministic Finalization and IDisposable post series. For the first example of a useful custom class which implements IDisposable, I will simply link to and reproduce Ian Griffith’s TimedLock — an enhancement of the C# lock statement which allows the specification of a timeout period instead of blocking forever while trying to obtain the lock. The code for TimedLock is reproduced below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 using System; using System. Read more...
Deterministic Finalization and IDisposable Part 1: The Basics
Deterministic Finalization and IDisposable csharp garbage collection
Published: 2005-02-11
Deterministic Finalization and IDisposable Part 1: The Basics
This is part 1/5 of my Deterministic Finalization and IDisposable post series. This topic has been covered many times by many others (such as here and here), so if you are familiar with C#’s using statement and IDisposable interface, feel free to skip this post. I’m writing this introduction to provide the necessary background information to set up a series of subsequent posts. Garbage collection, found in languages such as C# and Java (among many others), is a very useful feature: it largely alleviates the need for a programmer to manually handle resource management. Read more...