Tag Archive: .net

Empty Pattern

This thread on Msdn was one I came across, and I felt it needed a much better answer. His question in short, is what is the difference between null, Empty, and “” in C#. I assume that you know what null and "" are, so I’m going to focus on the meat of the question. So the obvious question is what is Empty? Let’s look deeper into some existing types that use this pattern.

System.String
String value = String.Empty;

System.Drawing.Rectangle
Rectangle value = Rectangle.Empty

I could go on, but I will stop there. There are a few things that types using this pattern have in common.

  • They are types that have value semantics
  • Empty is a public static readonly field
  • Empty’s type is the same as its containing type

Okay.. but what does all this mean. Empty is a public static readonly field that represents the default value for an instantiated type that has value semantics. This pattern is useful for two reasons. One, for value types, because value types are not nullable, it is an easy way to have access to the default value of that type, and is equivelent to calling default(T). And secondly, it is useful to find out if an instance of a type has been modified from its default value. Let’s take a deeper look at how this pattern applies to Value Types and Reference Types, and we’ll start with a value type.

public struct Point {
    public static readonly Point Empty = default(Point);
    public int X { get; set; } 
    public int Y { get; set; } 
}

For value types, since they cannot be null, it is good practice to use default(T) for declaring the empty field, however new Point() works just as well. Remember that default(T) for structs will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.

Point p1 = Point.Empty;    // {0,0}
Point p2 = new Point();    // {0,0}
Point p3 = default(Point); // {0,0}

All three lines of code are equivelent, except in regards to performance. Using Point.Empty we are not instantiating a new instance of Point, but the other two methods do. A minor detail, but important to note regardless.

Point p = Point.Empty;
p.X = 1;
p.Y = 1;

if (p != Point.Empty) {
    p.X = 0;
    p.Y = 0;
}

Now you can see how Empty is useful. Very easy to see if the point has been modified from its default value. We can see how useful this pattern is for structures, and how its used in existing types in .NET. What about reference types? The same practices apply, but there is a difference in how we should declare the static field, because reference types can be null, which is their default value.

public class Point {
    public static readonly Point Empty = new Point();
    public int X { get; set; } 
    public int Y { get; set; } 
}

In the above sample, we changed our Point from a value type to a reference type, but note line two. Instead of using default(T), we are using new Point(). This is because the default value for a reference type is null, which is great, but we don’t want the default value, we want its Empty value.

The next important change, is that we must make the type immutable. Using this pattern on a mutable reference type will have negative impact and wrong behaviors in your application. Remember that value types use copy semantics, reference types hold a reference to the underlying object in memory, so if we were to use the following code:

Point p = Point.Empty;
p.X = 2;

This would actually modify the value of Point.Empty to be {2,0}. For this pattern to be viable when using a reference type, it must be immutable.

public class Point {
    public Point(int x, int y) {
        X = x;
        Y = y;
    }
    public static readonly Point Empty = new Point();
    public int X { get; private set; } 
    public int Y { get; private set; } 
}

There’s not much else to say, hopefully by now you understand why this pattern exists, so let’s recap my DO’s and DO NOT’s for this pattern.

DO Implement an T.Empty field on types that have value semantics.
DO Make T.Empty public static readonly.
DO Use default(T) as the value for T.Empty when used with a struct.
DO NOT Use default(T) as the value for T.Empty when used with a class, use new T() instead.
DO NOT Use this pattern on mutable reference types. Use them on immutable reference types like System.String.
DO NOT Use this pattern on types where value semantics don’t make sense.

How Auto width Grid columns work with column spanning.

A friend of mine was wondering if he had encountered a bug in WPF today. What he was trying to do is have a Grid with four columns, each with a width of Auto, and have a TextBox fill the entire width of his Grid. Here was his Xaml.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.ColumnSpan="4" Grid.Row="0"
                Margin="5,6"
                HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" />

    <Button Grid.Row="1" Grid.Column="0" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="1" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="2" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="3" Margin="3" Content="Hello" />
</Grid>

What he wants is for his TextBox to take up the remaining width in the Grid. The way Auto works for a GridColumn‘s width, is that it sizes itself to the maximum width of its content. So in this case, the width of each column is that of the width of each button. Now because there are only four columns defined in the Grid, the TextBox can only span a maximum of four columns. The remainder of the Grid is undefined space that fills the Window, because the default behavior of a Grid is to fill its parent container.

So how do we get the TextBox to fill the undefined space? You define it. Add a fifth column with a * width, which means it will fill the remainder of the Grid space, and then we can set the TextBox to span all five columns, instead of the first four.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.ColumnSpan="5" Grid.Row="0"
                Margin="5,6"
                HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" />

    <Button Grid.Row="1" Grid.Column="0" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="1" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="2" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="3" Margin="3" Content="Hello" />
</Grid>

How to use Enum as an ItemsSource using a MarkupExtension.

There are a lot of different ways to use an Enum as a data source for some list, like a ComboBox. I’m going to demonstrate how to create a MarkupExtension that will make your life a lot easier in all your projects. To create a markup extension, create a class that derives from MarkupExtension and overrides ProvideValue(IServiceProvider). Next, add a constructor that takes a System.Type as a parameter, and a property called EnumType to store the type information.

namespace MarkupExtensionDemo.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Markup;
    
    [MarkupExtensionReturnType(typeof(System.Object[]))]
    internal class EnumExtension : MarkupExtension
    {
        public EnumExtension() {
        }

        public EnumExtension(Type enumType) {
            EnumType = enumType;
        }

        [ConstructorArgument("enumType")]
        public Type EnumType {
            get;
            set;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
 	        if (EnumType == null) {
                throw new System.ArgumentException("The enumeration's type is not set.");
            }

            return Enum.GetValues(EnumType);
        }
    }
}

The real work is done in the ProvideValue(IServiceProvider) method, which actually returns the collection of enumeration values. Now, in our Xaml, we can specify an Enum as an ItemsSource very easily. Let’s say we have the following Enum.

namespace MarkupExtensionDemo
{
    public enum Priority
    {
        Low,
        Medium,
        High
    }
}

We can use it in our Xaml like this.

<UserControl 
             x:Class="MarkupExtensionDemo.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:Extensions="clr-namespace:MarkupExtensionDemo.Extensions"
             xmlns:local="clr-namespace:MarkupExtensionDemo">

    <ComboBox ItemsSource="{Extensions:Enum local:Priority}" />

</UserControl>

It’s important to note that you need to include your namespaces so the types can be resolved. When the markup extension is reached, it executes the ProvideValue(IServiceProvider) method and returns the array of enumeration values to use as the items source.

Windows Communication Foundation

I recorded an hour and a half presentation on Windows Communication Foundation yesterday that you can view on YouTube here. The video is recorded in 1920×1080, and is uploaded at that quality. The presentation covers everything from what WCF is, to creating your first service and client, as well as a few other advanced subjects.

Resources
YouTube: http://www.youtube.com/watch?v=jaHc1Lbki-A&hd=1
PowerPoint: Windows Communication Foundation.pptx
Source Code: Routing Services.zip

Working with the WPF TextBlock control.

Introduction
Setting a TextBlock’s Content
Formatting Text
Using Controls with Formatted Text

Introduction

In WPF there are two very similar controls Label and TextBlock, and I’m going to cover TextBlock and why its so useful. First, what is the TextBlock control? A first look at the Msdn documentation.

Provides a lightweight control for displaying small amounts of flow content.

Well, that doesn’t tell that much about the control. A more accurate description would be that its a lightweight control for displaying various forms of formatted text and controls in a flow layout. Specifically, the TextBlock control can contain other controls, and arbitrary text that you can format with different font styles, colors, and brushes. Because it can contain other controls, it is actually much more than a `Text`Block, and I’m not sure why they named it TextBlock considering.

Setting a TextBlock’s Content

For demonstration, I will start with a small WPF Windows Application that contains just a TextBlock control containing the text Hello World!.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top"> 
            Hello World!
        </TextBlock>
    </Grid>
</Window>
TextBlockDemo_HelloWorld

An empty window with a TextBlock

There are two ways you can set text for a TextBlock. The first is the most obvious, and that is to set the Text property.

<TextBlock Text="Hello World!" HorizontalAlignment="Stretch" VerticalAlignment="Top">

The second is by setting the inner value of the control like I did in the demo application. Both methods give the same result for displaying Hello World!, but only setting the inner value of the TextBlock control gives us access to the true potential of the control. The Text property itself can only be used to display an arbitrary System.String. Shown below is the source code from the TextBlock metadata of its Text property.

//
// Summary:
//     Gets or sets the text contents of a System.Windows.Controls.TextBlock.
//
// Returns:
//     The text contents of this System.Windows.Controls.TextBlock. Note that all
//     non-text content is stripped out, resulting in a plain text representation
//     of the System.Windows.Controls.TextBlock contents. The default is System.String.Empty.
[Localizability(LocalizationCategory.Text)]
public string Text { get; set; }

Because the TextBlock can contain multiple controls by using its inner value, we can add things like buttons or other controls.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            Hello World!
            <Button Content="Click me!" />
        </TextBlock>
    </Grid>
</Window>

A TextBlock containing text along with a Button control.

One of the most common questions from those just entering the WPF world is why doesn’t the button display on a new line even though in the Xaml the Button element is on its own line? Placing elements on a new line doesn’t necessarily do anything, and for a TextBlock control, adding a new line is actually done using the LineBreak element.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            Hello World!
            <LineBreak />
            <Button Content="Click me!" />
        </TextBlock>
    </Grid>
</Window>

A TextBlock control with text, a button, and a line break.

I won’t cover any more about nested controls in the TextBlock. Once you understand that a control can contain other controls, the rest depends on your understanding of understanding the layout and styling mechanisms of WPF. The usefulness of truly comes from the ability to format strings of text without using multiple controls.

Formatting Text

Formatting text is done using an element called a Run which is defined as a inline-level flow content element intended to contain a run of formatted or unformatted text. Using a Run, you can style seperate segments of text using colors, brushes, and styles.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            <Run Foreground="Red">Hello</Run>
            <Run Foreground="Blue">World!</Run>
        </TextBlock>
    </Grid>
</Window>

A TextBlock containing the text 'Hello World!' split into two runs, one red and one blue.

You can see that it was very easy to style the text to be red and blue. Now let’s add a LinearGradientBrush to the second run and give it a larger font with a bold style.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            <Run Foreground="Red">Hello</Run>
            
            <LineBreak />
            
            <Run Text="World!" FontSize="24pt" FontWeight="Bold">
                <Run.Foreground>
                    <LinearGradientBrush StartPoint="0,1" EndPoint="0,0">
                        <GradientStop Offset="0" Color="Navy" />
                        <GradientStop Offset="1" Color="DodgerBlue" />
                    </LinearGradientBrush>
                </Run.Foreground>
            </Run>
        </TextBlock>
    </Grid>
</Window>

A TextBlock run with its Foreground set to a LinearGradientBrush

Just like the TextBlock, a Run can contain its text in either its Text property, or its inner value. Since we want to use its inner value to set some text effects, it was moved from the inner value to the Text property. The FontSize and FontWeight properties were also added, along with our Run.Foreground element that contains our linear gradient effect.

Using Controls with Formatted Text

Often times you may want to do something like have a piece of text actually contain a link to some resource. I had a need for this myself in one of my dialogs in my licensing modules; I need it to display a link to a product page. A TextBlock can contain both controls and runs, which makes for great flexibility. A Run however, cannot contain a control so its important to make note of that.

<Window x:Class="TextBlockDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top">
            <Run Text="This is some text containing a " />
            <Hyperlink NavigateUri="http://danderson.io/">link to a page.</Hyperlink>
        </TextBlock>
    </Grid>
</Window>

A TextBlock containing a HyperLink.

The cool thing about this is that because a HyperLink is its own control, it can contain its own styling and behaviors.

There’s not much else to say about the TextBlock because it really is a simple control. It’s just really flexible and when used correctly can be a very easy way to display lots of formatted text to a user. The ability to contain controls that can also have their own styles and behaviors is really cool, but I still think the WPF team should have chosen a better name than TextBlock, because its much more than just arbitrary text.

Avoiding a deadlock when creating a STA thread and using Dispatcher.

I have always been pretty articulate and careful when writing multi-threading code, but today I wrote my first deadlock that had me baffled for a few minutes. I’m working on a licensing dll that handles a lot of processing, and it also handles some user interface display using WPF Windows. I cannot guaruntee whether or not the calling thread will be a single-threaded apartment, because the assembly that implements it might be a console or a window, but the assembly doesn’t know which, or which threading model it uses. The good news is that System.Threading provides very rich types to be able to check for this as well as handle it.

First lets take a look at actually checking for the threading model, and creating an STA thread if needed.

if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) {
    Thread thread = new Thread(() => {
        // ...
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

You can see that the code to check for the current threading apartment isn’t anything hard, and neither is setting the apartment state. Now my requirement was that the WPF Window be shown modal by calling Window.ShowDialog so I could consume the DialogResult and continue processing in the licensing service. To do this I created the Window in the newly created STA thread.

if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) {
    ActivateWindowController controller = new ActivateWindowController();
    ActivateWindow window = null;

    bool? dialogResult = null;

    Thread thread = new Thread(() => {
        window = new ActivateWindow(controller);
        dialogResult = window.ShowDialog();
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
}

There’s nothing too exciting about any of this either. I’m using the Model-View-Controller (MVC) pattern so I have a ActivateWindowController that gets passed to the ActivateWindow constructor. Because we need the Window to run in a single-threaded apartment, I do the actual instantiation in the new Thread. Then I make a call to ShowDialog() and consume the result. The last bit is adding thread.Join(); so the calling thread is blocked until the new thread terminates, which is when the dialog is closed.

Now I’ll try to explain what ActivateWindowController does as best as I can. When ActivateWindow is loaded, the WPF stack invokes the Loaded event handler. The code isn’t anything special, so I’ll just show it.

public partial class ActivateWindow : Window
{
    /// <summary>
    /// Initializes a new instance of the DCOMProductions.Licensing.Windows.LicenseWindow class.
    /// </summary>
    public ActivateWindow(ActivateWindowController controller) {
        InitializeComponent();
        _controller = controller;
    }

    #region Controller Members

    private ActivateWindowController _controller;

    private void Window_Loaded(object sender, RoutedEventArgs e) {
        _controller.ActivateComplete += ActivateComplete;
        _controller.Activate();
    }

    private void ActivateComplete(object sender, ActivateWindowController.ActivateEventArgs e) {
        DialogResult = e.Result == ActivationResult.Passed ? true : false;
    }

    #endregion
}

When the Loaded event handler is invoked, a call to ActivateWindowController.Activate() is made. What this method does is spin off a new Task by calling Task.Factory.StartNew(...) and consumes a WCF service. In short, it means another thread. When the task completes, it invokes Task.ContinueWith(...) which is responsible for wrapping up the result and delegating everything to the proper thread.

.ContinueWith((task) => {
    CloseDialogCallback method = new CloseDialogCallback(() => {
        OnActivateComplete(new ActivateEventArgs(result));
    });
    _Dispatcher.BeginInvoke(method, null);
});

Now it is important to note here that _Dispatcher is a private instance that was initialized in the constructor of ActivateWindowController. In short, the dispatcher lives on the UI thread of the Window. The dispatcher is required to delegate calls to the correct thread, in this case we want to delegate the callback method to the UI thread. And remember, the UI thread is the STA thread I created earlier.

I highlighted the last line, because this is where the deadlock is introduced. When _Dispatcher.BeginInvoke(method, null); is called, it schedules asynchronously the callback to be executed on the thread that the dispatcher was created on. And remember, the thread that _Dispatcher was created on is the same thread that the ActivateWindowController instance was created on. Let’s double check that.

if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) {
    ActivateWindowController controller = new ActivateWindowController();
    ActivateWindow window = null;

    bool? dialogResult = null;

    Thread thread = new Thread(() => {
        window = new ActivateWindow(controller);
        dialogResult = window.ShowDialog();
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
}

Well, hopefully by now you realize the problem and why there is a deadlock. ActivateWindowController is not being instantiated on our STA thread. So what’s happening here is when _Dispatcher.BeginInvoke is called, it is scheduling the callback to execute on the same thread we told to block by calling thread.Join(). Because that thread is blocked and the dialog can’t return until the callback is executed by the dispatcher, I have a blocked thread and a scheduled callback that will never run; eg. a deadlock.

The fix is to instantiate ActivateWindowController on the STA thread I created which is where we want the dispatcher to delegate the callback to anyway. This resolves the deadlock problem. It’s important to watch out for little quirks like this. It didn’t take me long to realize what created the deadlock, but I think on most days it would have taken me much longer to figure it out. The most important thing to remember is that this is not specific to a Dispatcher, and that it applies to multi-threading regardless.

Showing a splash screen in WPF from an external assembly or class library.

This isn’t anything special, but the documentation on Msdn for System.Windows.SplashScreen is lacking. Basically I am writing a licensing system and during debugging the WPF stack can take many seconds to load. When making changes to this system sometimes it may result in a failure, but I may not see it for a few seconds. I wanted something to display during this time period so I know at least something is going on.

I knew that WPF has built-in support for splash screens by setting the Build Action of an image in my project to Splash Screen in the properties window, but the problem is that this only works for the project the image is embedded into, and only if its a WPF Application project. My requirements are that I can display the splash screen from my licensing dll (class library) when my licensing service is invoked. This means that the licensing dll would contain the image to display, and contain the logic to show the splash.

Luckily, SplashScreen exposes a SplashScreen(Assembly, String) constructor which allows you to do just this. To accomplish this task, all you need to do is add your image to your class library project, set its build action to Splash Screen, and then write three lines of code.

Assembly asm = Assembly.GetAssembly(GetType());
SplashScreen splash = new SplashScreen(asm, "SplashScreen.png");
splash.Show(true);

The first line is simple; we are just getting the assembly that contains the splash resource (in this case my licensing library). The second line takes the assembly as an argument, and we pass in the name of the image. Next we simply call splash.Show(true); which actually displays the image, and because we passed in true as the argument, it will automatically be closed by the WPF stack once the first window is constructed, loaded, and displayed.

Make sure that you add your image to the root of your project, so that the WPF stack can find it.

I haven’t looked into it because I don’t want to spend a lot of time on a task that doesn’t mean much, but placing the image at other hierarchical locations in your project structure can cause the embedded resource path string to change, and it may not be found by the WPF stack internally. It’s probably possible to specify a qualified path using the second constructor parameter, but I was not able to get it to work using a fully qualified resource path string.

Getting a stream to a resource without copying the contents into memory.

If you have ever added a resource file to your project through the Project Properties > Resources tab, then you have used a ResourceManager. The resource manager allows you to access resources in your application simply through a static resource manager. This line of code should look familiar.

string message = Properties.Resources.MyDialogText;

This is not just convenient, it’s just plain easy. The problem is that when something is just plain easy, there are often tradoffs, and here there is a big one. Let’s assume we have a binary resource (a file) that is 7764480 bytes (7.40 megabytes) called ‘Bootstrapper.exe’. Now normally you would get the resource just by doing byte[] bytes = Properties.Resources.Bootstrapper. What happens here is you are invoking an instance of ResourceManager that returns the bytes to our Bootstrapper.exe file. The tradoff of such an easy way of getting the resource, is that it just created a copy of the data into memory, adding 7.40 megabytes to our application’s Working Set memory. Let’s look at a bare-bone sample application.

namespace ResourceManagerSample
{
    using System;

    internal static class Program
    {
        public static void Main(string[] args) {
            Byte[] bytes = Properties.Resources.Bootstrapper;
        }
    }
}

Stepping through this code and stopping on line 11, just before the statement is executed, the application’s working set is 47,964 bytes. Execute the statement by stepping to the end of the method body, and the working set just increased from 47,964 bytes to 63,364 bytes. What happened is the ResourceManager just returned us a copy of the binary resource contents. If you were working with a binary resource that was say, a gigabyte in size, your application’s working set memory would have just increased by a gigabyte.

Let’s take a look at why this happens by looking at the internals of the ResourceManager class. The two main methods we are interested in are Object GetObject(String, CultureInfo, Boolean) and UnmanagedMemoryStream GetStream(String, CultureInfo).

private Object GetObject(String name, CultureInfo culture, bool wrapUnmanagedMemStream) {
    ...
    Object value = rs.GetObject(name, _ignoreCase);
    ... 
}

I stripped the method down to the important line, which is rs.GetObject(name, _ignoreCase);. What happens here is the ResourceManager makes a call to ResourceSet.GetObject, which is what actually gets the resource as a System.Object. The internals of the ResourceSet are not that interesting either, because all it does is get the object from a HashTable.

public virtual Object GetObject(String name, bool ignoreCase)
{
    Hashtable copyOfTable = Table;  // Avoid a race with Dispose
    if (copyOfTable == null) 
        throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
    if (name==null) 
        throw new ArgumentNullException("name"); 

    Object obj = copyOfTable[name]; 
    ...
    return caseTable[name];
}

As you can see, the public call in ResourceManager simply calls into ResourceSet which returns the actual resource as an object. Because its returning the actual object, memory is allocated for the resource, thus increasing our working set. I won’t show the internals of ResourceManager.GetStream because all that does is actually make a call to GetObject as well, so it boils down to the same thing. The difference is that GetObject can return just an object (a System.String for example), or it can return an UnmanagedMemoryStream. GetStream obviously only returns a stream.

Intrinsically the problem is that ResourceManager creates a heavy memory footprint, and it isn’t flexible enough to grab only a pointer to the resource instead of an actual instance copy. We can get around this problem by using embedded resources.

Embedded resources are embedded into the assembly manifest at compile-time and accessible directly through the assembly. Working with ResX resource files, resources are still embedded but are accessible through a ResourceManager which I already discussed. ResX resources are not available directly through the assembly such as calling Assembly.GetManifestResourceNames. In either case, resources still get embedded to the assembly at compile-time, but each is accessible in a different way.

With avoiding using a ResX resource file and ResourceManager, you can set the Build Action of the resource by right-clicking the file, and setting Build Action in the properties Window to Embedded Resource.

It’s important that you do not use a ResX resource file and set the resource to embedded. This will result in you having the same resource embedded twice, increasing the size of your assembly 2x.

With embedded resources, we can access them by using the Assembly class, and calling Assembly.GetManifestResourceNames() and Assembly.GetManifestResourceStream(String).

private static UnmanagedMemoryStream GetResourceStream(String name) {
    Assembly assembly = Assembly.GetExecutingAssembly();

    string[] resources = assembly.GetManifestResourceNames();
    string resource = resources.SingleOrDefault(r => r.EndsWith(name, StringComparison.CurrentCultureIgnoreCase));

    if (resource == null) {
        throw new System.ArgumentException("The specified resource does not exist in the assembly manifest.", "name");
    }

    return (UnmanagedMemoryStream)assembly.GetManifestResourceStream(resource);
}

It’s important to note how embedded resource names are stored in the manifest. When you set the build action on a file in your project to Embedded Resource, a resource name is created in the manifest that uniquely identifies the resource. The name will take on the project and foldier hierarchy and is in the format of a namespace. If the Bootstrapper.exe resource is in the root directory of the project named RresourceManagerSample, the resource identifier will be ResourceManagerSample.Bootstrapper.exe. And if you had it in a subfolder of the project called Resources it would be ResourceManagerSample.Resources.Bootstrapper.exe.

In the example method I wrote it takes a System.String name parameter, and checks the end of each resource string for a match, and throws a System.ArgumentException if the resource does not exist. The rest of the method is simple, because it just returns an UnmanagedMemoryStream by calling assembly.GetManifestResourceStream().

The whole point of this is that by using embedded resources and reflection, we get the resource as an UnmanagedMemoryStream without having the entire resource copied into memory. Before when using a ResourceManager remember that it would copy the entire resource into memory. This method does not do that, and looking at the internals of Assembly.GetManifestResourceStream() tells us why.

internal unsafe virtual Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck) 
{ 
    ulong length = 0;
    byte* pbInMemoryResource = GetResource(name, out length, ref stackMark, skipSecurityCheck); 

    if (pbInMemoryResource != null) {
        if (length > Int64.MaxValue) 
            throw new NotImplementedException(Environment.GetResourceString("NotImplemented_ResourcesLongerThan2^63"));
        return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read, true); 
    }

    return null; 
}

You can immediately see that instead of obtaining an instance copy of the resource, you get a nice pointer to the resource instead. Looking further into the implementation you can see that the call to GetResource actually makes a call to an external method called _GetResource.

[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe extern byte* _GetResource(String resourceName, out ulong length,
                                        ref StackCrawlMark stackMark, 
                                        bool skipSecurityCheck);

If you don’t know what extern does, it is easily explained in 10.6.7 of the C# specification.

When a method declaration includes an extern modifier, that method is said to be an external method. External methods are implemented externally, typically using a language other than C#.

Unfortunately this means I cannot show you the source to _GetResource, but its likely to be in native C++. The most important aspect of GetManifestResourceStream() is that it returns a pointer to the resource, rather than a instance copy like ResourceManager does. Because of this, the contents of our Bootstrapper.exe resource need not be fully loaded and the magic happens in some external C++ code.

Thanks to such magic under the hood, we can now call our method just as easily as using a ResourceManager.

namespace ResourceManagerSample
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    internal static class Program
    {
        private static UnmanagedMemoryStream GetResourceStream(String name) {
            Assembly assembly = Assembly.GetExecutingAssembly();

            string[] resources = assembly.GetManifestResourceNames();
            string resource = resources.SingleOrDefault(r => r.EndsWith(name, StringComparison.CurrentCultureIgnoreCase));

            if (resource == null) {
                throw new System.ArgumentException("The specified resource does not exist in the assembly manifest.", "name");
            }

            return (UnmanagedMemoryStream)assembly.GetManifestResourceStream(resource);
        }

        public static void Main(string[] args) {
            UnmanagedMemoryStream stream = GetResourceStream("Bootstrapper.exe");
        }
    }
}

Except now stepping through the code, you can step through to the end of the method body and see that the UnmanagedMemoryStream is instantiated and to the appropriate size, but our working set memory has not allocated anything extra. How we can allocate memory by reading data from our stream as needed.

public static void Main(string[] args) {
    UnmanagedMemoryStream stream = GetResourceStream("Bootstrapper.exe");

    byte[] buffer = new byte[stream.Length];

    stream.Read(buffer, 0, buffer.Length);
}

Stepping through the code and stopping at stream.Read(buffer, 0, buffer.Length); just before the statement executes will show that our working set has remained the same. Executing the statement reads the contents into our buffer allocating memory as its read. Only reading from the stream will increase our working set as we need the resource bytes. This is much more efficient than using a ResourceManager, and not hard to implement.

The question now is when to use a ResourceManager with ResX files, and when to use embedded resources. I’ve not benchmarked one or the other in terms of speed performance, but the whole point was about memory footprint. You should definitely use a ResourceManager if your resources are small, short lived, and you need the ease of being able to access them directly through the ResourceManager class, and by calling GetObject and GetStream. If your resources are very large and your application’s working set memory might be an issue, you will want to use embedded resources and reflection.

Generally in a project you will use one or the other, and seldom both types of resources, but there isn’t anything wrong with using both types. It all depends on your requirements, and neither or solves every problem. The trick is picking which one is best for your requirements, just like picking an appropriate programming language to solve a problem.

When is it appropriate to override ToString?

Microsoft .NET

This question was asked on StackOverflow. Because my answer was upvoted well, I decided include it as a blog post.

First, let’s talk about what ToString actually is. The ToString method lives in System.Object, and because System.Object is the base class for all objects in C#, all objects have the ToString method. Some objects expose ToString overloads that accept parameters like CultureInfo, or formatting options, but for the most part most objects will have the default overload that accepts no parameters.

ToString was designed to do one thing: display a representation of an objects state. This is explicitly why it lives in System.Object. That is the only use for ToString, and it should be used. It should not be used to do anything else like change an objects state or apply behaviors.

These are the official guidelines from the .NET Development Series from Microsoft, specifically included in the Framework Design Guidelines book. I highly recommend you buy and read it in full, multiple times.

AVOID throwing exceptions from ToString

CONSIDER returning a unique string associated with the instance.

CONSIDER having the output of ToString be a valid input for any parsing methods on this type.

DO ensure that ToString has no observable side effects.

DO report security-sensitive information through an override of ToString only after demanding an appropriate permission. If the permission demand fails, return a string excluding security-sensitive information.

The Object.ToString method is intended to be used for general display and debugging purposes. The default implementation simply provides the object type name. The default implementation is not very useful, and it is recommended that the method be overridden.

DO override ToString whenever an interesting human-readable string can be returned. The default implementation is not very useful, and a custom implementation can almost always provide more value.

DO prefer a friendly name over a unique but not readable ID.

DO try to keep the string returned from ToString short. The debugger uses ToString to get a textual representation of an object to be shown to the developer. If the string is longer than the debugger can display, the debugging experience is hindered.

DO string formatting based on the current thread culture when returning culture-dependent information.

DO provide overload ToString(string format), or implement IFormattable, if the string return from ToString is culture-sensitive or there are various ways to format the string. For example, DateTime provides the overload and implements IFormattable.

DO NOT return an empty string or null from ToString