Wednesday, September 20, 2017

.NET IsAssignableFrom

For some reason I have a mental block remembering which way .NET's IsAssignableFrom() function works, so, using the excellent LINQPad and the following code snippet, I came up with the following results:
typeof(BaseClass).IsAssignableFrom(typeof(DerivedClass)) // true
typeof(DerivedClass).IsAssignableFrom(typeof(BaseClass)) // false
Code:
void Main()
{
 typeof(BaseClass).IsAssignableFrom(typeof(DerivedClass)).Dump("typeof(BaseClass).IsAssignableFrom(typeof(DerivedClass))");
 typeof(DerivedClass).IsAssignableFrom(typeof(BaseClass)).Dump("typeof(DerivedClass).IsAssignableFrom(typeof(BaseClass))");
}
    
class BaseClass { }
class DerivedClass : BaseClass { }

Thursday, June 08, 2017

C# 6 String Interpolation Does Not Concatenate

Well, I learned something new today that's slightly disappointing. I had thought that C# 6 string interpolation concatenated strings or perhaps used the StringBuilder or some such under the hood. It turns out it merely creates a good, old-fashioned String.Format statement out of it.

Given this source code:

The resulting IL (compiled) code is the following:

Note the following two statements:
ldstr       "A{0}C"
call        System.String.Format
These indicate that String.Format is being called with the familiar-looking format string "A{0}C".


To compile the C# code and create IL code, I used Joe Albahari's excellent LINQPad program.