Friday Links 0.0.17 - Disposable Object Initializers, Razor Sections, SQL String Searches

This is based on an email I send my .NET team at work

Happy Friday,

Can you wrap an object initializer in a using statement?

The first answer on this StackExchange question analyses how the C# using statement operates together with the object initializer pattern. The goal was to address the correctness of this pattern:

using(var obj = new SomeObject() { SomeProperty = "Foo", SomeThingElse = "Bar" }) {
    // do some work

What happens if one of those property setters throws? Is the object properly disposed or not? What happens if the constructor throws? What’s the safe way to initialize an object for a using statement and set its properties?

You should go check out the analysis, but the TL;DR is that in that example, an exception thrown in one of those property setters (SomeProperty or SometThingElse) will result in the object not being Disposed by the using block.

The safe way to do it is:

using(var obj = new SomeObject())
    obj.SomeProperty = "Foo";
    obj.SomeThingElse = "Bar";
    // do some work

Layouts and Sections in Razor

This is a pretty old article, but it discusses a feature of razor we don’t see too much: Sections. A Section lets your base layout define placeholder areas where child razor pages can insert content.

The example in this article uses it for a sidebar placeholder that individual pages can inject their own set of links.

A use case I’ve used is for providing a section in the <head> tag so that child pages can inject custom javascript resources they need. Sometimes you have a page that needs a particular script and you don’t want to include it on every page. You just provide a placeholder where that page can stick it’s own <script> tag.

Sections can get out of hand if they’re used for a lot of layout features: it can make it hard to find where content is coming from. I’d favor it for smaller placeholders like the script example, and use nested layouts with the RenderBody() call as much as possible.

Searching Strings in SQL Server is Expensive

Brent Ozar looks at searching the Stack Overflow database for users by name and demonstrates some of the costs of using wildcards (%) on string fields.

He shows that a trailing wildcard like 'Foo%' is not too expensive because the server can seek right to Foo in the index and drastically reduce the number of index entries it has to consider.

However, a leading wildcard like %Foo% is way more expensive: SQL Server has to scan the entire index AND spend a lot of CPU time opening each string and searching all the way through it looking for a match.

He follows up with some tips for migrating to a different schema that can help address these performance problems. Check it out!