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!
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!
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): [...]
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) [...]
Update Due to minor demand, the code is also available: BigNum source. Please note that I haven’t actually touched the code since it was first written. I’m sure there’s some things that don’t work properly. If you’re doing anything big with this you probably want to write some ‘destructive’ update functions for adding, etc. At [...]