Posts

Showing posts from April, 2010

C# Creating a Singleton

A lot of people talk trash about the Singleton and how it should be avoided like the plague. I think like a lot of things it has its place and can be used effectively in certain situations. I'm going to leave what those situations are alone for the time being and just focus on creating a nice thread safe lazy init singleton class. public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return Nested.instance; } } class Nested { // Use an explicit static constructor to tell the C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } }

Binding to a DataGridView with a custom collection

Image
Often times I find the need to bind a custom collection to a datagridview in a windows form. .Net makes this easy and with some simple code we can achieve some pretty quick results. First drop a DataGridView onto your form. Click the little white arrow on the top right of the grid and select Choose Data Source. This should bring up wizard that allows you to select what you want to bind to the grid. Select Object and click Next. Now select the class you want to bind too. You can select from all the existing references in your project or add a new one by clicking Add Reference. When you've selected the class to use click the Finish button. Now that you've got the design done let's write some code to show our data in the grid. I have created a custom collection called Playlists that contains a list of Playlist items. My datagrid is bound to this collection and uses its public properties as the values for the columns. public class Playlist { private String _