porges

Tag: .net

Objects can be collected while their instance methods are still executing

In Peter Ritchie’s post Dispose Pattern and “Set large fields to null”, he states the following (my highlighting): At face value, setting a field to null means that the referenced object is now unrooted from the class that owns the field and, if that was the last root of that reference, the Garbage Collector (GC) [...]

Casting in .NET via object mutation

In this post, we will see how to make the following code fail: object it = new SomeStruct { Item = 1 };   Floatsy(it);   Console.WriteLine(((SomeStruct)it).Item); At runtime, it will throw an InvalidCastException!

Implementing IEnumerable easily

Say that you’re implementing a linked list, and you want an enumerator: public IEnumerator<T> GetEnumerator() { return new Stream<T,Node>(first, node => node.next == null ? null : Tuple.Of(node.next, node.datum).AsNullable()); } This uses the following utility class to implement the enumerator in one line (along with some code for Tuples and an extension method for structs): [...]

object.Equals handles null values correctly

Here’s the source code, as disassembled by Reflector: public static bool Equals(object objA, object objB) { return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB))); } It seems that not even Microsoft knows this! I spotted this code, from ASP.NET’s MVC implementation, on Scott Hanselman’s blog: return (other != null) [...]