Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Sunday, 2 June 2013

Hide your methods being tested using InternalsVisibleTo

It is not necessary to expose all methods being tested as public when using an external test project. By using the assembly attribute InternalsVisibleTo and specifying the namespace of the "friend" assembly, the visibility of the methods can then be reduced to internal, hiding them from all other assemblies.

In the project's AssemblyInfo.cs

[assembly: InternalsVisibleTo("MyAssembly.Tests")]
Saturday, 1 June 2013

Converting a type name into a readable string

Ever wanted to print a type name as text that the would be suitable for users? For example, converting the type name "SomeTypeName" to "Some type name".

I've come up with a pretty nice method to convert type names in to nice strings. The algorithm loops through each character in the string and determines whether to place the character as lower case or upper case and whether to insert a space based on the casing of the character and those surrounding it.

Examples

  • "TypeName" → "Type name"
  • "ABCTypeName" → "ABC type name"
  • "TypeABCName" → "Type ABC name"
  • "IMakeStuff" → "I make stuff"
Monday, 29 April 2013

Use .Any() in your LINQ to SQL queries

When using LINQ to SQL to check whether either no records exist or at least 1 record exists, be sure to prefer Any() over Count() as the SQL will be optimised to only get the information required. Any() will use EXISTS in SQL which stops as soon as a record is found whereas Count() uses COUNT(*) which goes through all the records to get the number matching the query.

Consider the following code samples:

var q1 = TableName.Count() > 0;

var q2 = TableName.Any();

They will produce the following SQL:

-- q1
SELECT COUNT(*) AS [value]
FROM [TableName] AS [t0]

-- q1
SELECT
    (CASE
        WHEN EXISTS(
            SELECT NULL AS [EMPTY]
            FROM [TableName] AS [t0]
            ) THEN 1
        ELSE 0
     END) AS [value] As you can see the second sample produces some admittedly uglier SQL but is much more efficient.
 
Sunday, 28 April 2013

Merging Dictionary objects

Say you have two (or more) Dictionary objects and want their contents merged, this can be done with LINQ very conveniently like so.

var mergedDictionary = dictionaries
    .SelectMany(e => e)
    .ToLookup(e => e.Key, e => e.Value)
    .ToDictionary(e => e.Key, e => e.First());

There is a major issue with this method though in that it's quite horrible performance-wise, the reason being because of the amount of conversions and unnecessary work that is happening. Firstly SelectMany is flattening the IEnumerables into a single IEnumerable, then we're converting the new IEnumerable into a Lookup and then we're converting the Lookup into a Dictionary taking only the first value for any key in the Lookup to resolve duplicates.

This is one of the problems with LINQ, everything is so simple and easy to use, but if you don't understand what is going on then a LINQ query can have a serious hit on the performance of an algorithm.

Sunday, 17 March 2013

C# passing a reference type by ref

You may ask yourself why you would ever want to pass a reference type into a method using the ref keyword, or why the C# compiler even allows this. Using ref on a reference type is actually slightly different to not using it. The difference is that the ref keyword makes it a reference (pointer) to the variable, not just the object. This allows assigning to the source variable of the parameter from within the method.

Sunday, 3 March 2013

Converting a string to the 'best-fitting' type

I answered a pretty interesting question on Stack Overflow yesterday, creating a method that takes a string and returns the value converted to the 'best-fitting' type out of a set of types boxed in dynamic. Here is the full question:

I have been playing around with converting a string to a value type in .NET, where the resulting value type is unknown. The problem I have encountered in my code is that I need a method which accepts a string, and uses a "best fit" approach to populate the resulting value type. Should the mechanism not find a suitable match, the string is returned.

This is what I have come up with:

public static dynamic ConvertToType(string value)
{
    Type[] types = new Type[]
    {
        typeof(System.SByte),
        typeof(System.Byte),
        typeof(System.Int16),
        typeof(System.UInt16),
        typeof(System.Int32),
        typeof(System.UInt32),
        typeof(System.Int64),
        typeof(System.UInt64),
        typeof(System.Single),
        typeof(System.Double),
        typeof(System.Decimal),
        typeof(System.DateTime),
        typeof(System.Guid)
    };
    foreach (Type type in types)
    {
         try
         {
               return Convert.ChangeType(value, type);
         }
         catch (Exception)
         {
             continue;
         }
    }
    return value;
}

I feel that this approach is probably not best practice because it can only match against the predefined types.

Usually I have found that .NET accommodates this functionality in a better way than my implementation, so my question is: are there any better approaches to this problem and/or is this functionality implemented better in .NET?

Intelligent type conversion in .NET, series0ne

Sunday, 24 February 2013

What backing data structures the .NET collections use

I've compiled some information about time complexity and underlying data structures of .NET simple collections and dictionaries. It was difficult to find some of this information on official sources like MSDN and non-official sources seemed to differ, so I used reflector and actually had a look at the .NET framework code to confirm these cases.

Simple collections

TypeData structureNotes
List<T>ArrayA regular list using a dynamic array
SortedSet<T>Red-black treeA list stored using a red-black tree

Time complexity

TypeGet ([i])FindAddInsertRemove
List\(O(1)\)\(O(n)\)\(O(1)\)*\(O(n)\)\(O(n)\)
SortedSetN/A\(O(\log n)\)\(O(\log n)\)\(O(\log n)\)\(O(\log n)\)
  • List.Add is O(n) when adding beyond the array's capacity.

Dictionaries

Dictionaries or hash tables are ideal when you either need to access the data via an arbitrary key or you need fast deletion and insertion. Note that this section doesn't the Lookup class which stores a collection of items against a key.

TypeData structureNotes
HashSet<T>Hash tableA hash table where the key is the object itself
Dictionary<TKey, TValue>Hash tableA hash table using a key not necessarily on the object being stored
SortedList<TKey, TValue>ArrayThe same as Dictionary only items and their keys are stored sorted arrays
SortedDictionary<TKey, TValue>Red-black treeThe same as Dictionary only items and their keys are stored in a red-black tree. Uses SortedSet behind the scenes

Time complexity

TypeFind by keyRemoveAdd
HashSet\(O(1)\)*\(O(1)\)*\(O(1)\)**
Dictionary\(O(1)\)*\(O(1)\)*\(O(1)\)**
SortedList\(O(\log n)\)\(O(n)\)\(O(n)\)
SortedDictionary\(O(\log n)\)\(O(\log n)\)\(O(\log n)\)
  • \(O(n)\) with collision** \(O(n)\) with collision or when adding beyond the array's capacity.

SortedList vs SortedDictionary

SortedList and SortedDictionary are best used when you need order to the items that you're storing. Here is a pretty detailed comparison from Microsoft:

The SortedList<TKey, TValue> generic class is an array of key/value pairs with \(O(\log n)\) retrieval, where \(n\) is the number of elements in the dictionary. In this, it is similar to the SortedDictionary<TKey, TValue> generic class. The two classes have similar object models, and both have \(O(\log n)\) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:

  • SortedList<TKey, TValue> uses less memory than SortedDictionary<TKey, TValue>.
  • SortedDictionary<TKey, TValue> has faster insertion and removal operations for unsorted data, \(O(\log n)\) as opposed to \(O(n)\) for SortedList<TKey, TValue>.
  • If the list is populated all at once from sorted data, SortedList<TKey, TValue> is faster than SortedDictionary<TKey, TValue>.

Another difference between the SortedDictionary<TKey, TValue> and SortedList<TKey, TValue> classes is that SortedList<TKey, TValue> supports efficient indexed retrieval of keys and values through the collections returned by the Keys and Values properties. It is not necessary to regenerate the lists when the properties are accessed, because the lists are just wrappers for the internal arrays of keys and values.

MSDN - SortedList, Microsoft

References

Thursday, 14 February 2013

Polymorphism, methods, interfaces and concrete types

I answered a question on Stack Overflow a couple of days ago and it sparked memories of several years ago when I was new to the industry. Something that confused me a little when starting out was around the use of interfaces. All of a sudden they started popping up in mass quantity as I started working on projects of significant size.

I wish someone had explained this to me back then. When deciding the parameters and return types of your methods, the parameters should be as abstract as possible and your return type should be as concrete as possible. The reason for this is to enable the most flexibility in your application.

Consider the example given in the SO question,

Why does IEnumerable.ToList<T>() return List<T> instead of IList<T>?

Returning a concrete List<T> that implements IList<T> only gives the method consumer more information. Given the definition of of List<T>

[SerializableAttribute] public class List<T> : IList<T>, ICollection<T>,
    IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>,
    IEnumerable<T>, IEnumerable

Returning as a List<T> gives us the ability to call members on all of these interfaces in addition to on List<T> itself. For example we could only use List.BinarySearch(T) on a List<T>, as it exists in List<T> but not in IList<T>.

Likewise with parameters, the more abstract they are the more types can be passed in. If we only need to look through a collection of data in no particular order we should use the IEnumerable<T> as the parameter type instead of a regular List<T> This allows much more flexibility when consuming the method, we could pass in a List<T> or a SortedSet<T> or a HashSet<T> etc. as they all implement the IEnumerable<T> interface.

In general to maximize the flexibility of our methods, we should take the most abstract types as parameters (only the things we're going to use) and return the least abstract type possible (to allow a more functional return object).

Sunday, 3 February 2013

Go to active document in Visual Studio 2012 solution explorer

Finally! Visual Studio natively supports jumping to the active document in the solution explorer with Visual Studio 2012. The command is called "Sync with Active Document" and can be accessed from the Solution Explorer toolbar.

Go to active document in solution explorer

The default shortcut is Ctrl + [, S and can be customised by modifying the SolutionExplorer.SyncWithActiveDocument command in keyboard options (Tools -> Customise -> Keyboard)

Sync active document customise
Friday, 1 February 2013

Using enum as a generic type

Unfortunately if you want to use an enum as a generic type, the obvious way of doing it doesn't work.

private void Method<TEnum>()
    where TEnum : enum

enum is treated as a special type and Microsoft haven't implemented this (yet). However, it is possible to use enums in generics. The MSDN article for Enum gives the following type definition for the class Enum.

[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Enum : ValueType,
 IComparable, IFormattable, IConvertible

This definition can be used to get enums working as generic types by constraining the generic type to those of Enum. Note that we can not constrain to type ValueType due to a 'special class' rule in .NET, but we can use struct instead to get around this.

private void Method<TEnum>()
    where TEnum : struct, IConvertible, IComparable, IFormattable

The above still allows some errors to get through the compilation process, as we could specify the type of a struct that implements the IComparable, IFormattable and IConvertable interfaces. We can check the type of TEnum and confirm at runtime if it is an enum before doing any work.

private void Method<TEnum>()
    where TEnum : struct, IConvertible, IComparable, IFormattable
{
    if (!typeof(TEnum).IsEnum)
    {
        throw new ArgumentException("TEnum must be an enum.");
    }

    // ...
}

I'm not aware of a way around this that could guarantee 100% type-safety at runtime but it isn't really a big problem. After all, what are the chances that we are going to accidentally pass in a struct that implements the three interfaces.

Further reading

Tuesday, 22 January 2013

Entity framework delete all entities extension method

Unfortunately when deleting items in entity framework the SQL commands are issued as single DELETE statements for each entity. This really becomes a bottleneck when there are a several thousand items. This handy set of extension methods allows convenient and efficient deletion of all entities for a particular type T. The GetTableName<T> used function even takes into account table mappings set up with the ModelBuilder.

Thanks to Rul Jarimba on StackOverflow for the GetTableName&ltT> function.
public static void DeleteAllEntities<T>(this DbContext db)
    where T : class
{
    var adapter = (IObjectContextAdapter)db;
    var objectContext = adapter.ObjectContext;
    var sql = string.Format("DELETE FROM {0}", objectContext.GetTableName<T>());
    var entityConnection = objectContext.ExecuteStoreCommand(sql);
}

public static string GetTableName<T>(this ObjectContext context) 
    where T : class
{
    string sql = context.CreateObjectSet<T>().ToTraceString();
    Regex regex = new Regex("FROM (?<table>.*) AS");
    Match match = regex.Match(sql);

    string table = match.Groups["table"].Value;
    return table;
}
Sunday, 20 January 2013

A List<T>.BinarySearch extension that takes a lambda expression

I was thinking the other day how inconvenient it is to use List<T>.BinarySearch if you don't want to use the default comparer of T, needing to go and create a new class that implements IComparer<T>. Seems overly messy to require a whole new class just to do the binary search.

So I did a little research to see if there was a way around it and found this Jon Skeet answer (obviously) on StackOverflow. It gives a nice generic class that we can instantiate with a Comparison object and pass that into the BinarySearch method. I extended Jon's answer to take a lambda expression instead, much like you can do with List.Sort.
Wednesday, 16 January 2013

Manipulating the size of List<T>

.NET allows us to set the size of a List<T> in the constructor if we know the capacity ahead of time. This will save the List's inner (dynamic) array from being reassigned (and copied) when items are added. While usually this will make a minuscule change to your program, if the list is large enough it saves quite a few operations.

The capacity constructor runs in O(n) time. Whereas Add(T) runs in O(1) time or O(n) time when the capacity needs to be increased.

Sunday, 13 January 2013

Start using System.Threadng.Tasks.Parallel now!

If you haven't experienced the power of the System.Threading.Tasks namespace new in .NET 4 you're missing out. This post is about the Parallel class which takes all of the complexity out of the seemingly simple task of running multiple functions in parallel.

Before we get into it, it's important to understand understand how the Action generic class works first. An Action is basically a method that returns void.

Invoke(Action[] actions)

With the Invoke method you can simply pass in an array of Action objects and the method will return once all the Actions have completed.
Action[] actions = new Action[3];
actions[0] = () => DoSomething();
actions[1] = () => DoSomethingElse();
actions[2] = () => DoSomethingAgain();

Parallel.Invoke(actions);
Thursday, 20 December 2012

Use razor comments in MVC views not HTML comments

Make sure for code documentation you use the razor-style comments in your ASP.NET MVC views, not HTML-style comments. Regular HTML comments will be sent to the client which would increase the page size and expose unnecessary implementation details to the end-user, razor comments are kept server-side.

Good:
@* Comment *@

Bad:
<!-- Comment -->
Sunday, 16 December 2012

ASP.NET MVC display and editor templates

Display templates

MVC has a bunch of handy helpers that we can use to create our views more efficiently. One such helper are the display templates that are used within views.

@Html.DisplayFor(e => e.Username)

The DisplayFor(Func<TModel, TValue> expression) function uses the type of the property in the expression to display the property value.

<!-- DisplayFor on string UserName = "daniel.imms" -->
<span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true">daniel.imms</span>
Monday, 17 September 2012

Custom helper for surrounding a block in markup with MVC

You may have seen or used the following code in your MVC applications:
@using (Html.BeginForm())
{
    // ...
}
It surrounds the markup inside the block with a <form> tag and includes attributes based on what is passed through the parameter list. The way it works is HtmlHelper.BeginForm() returns a MvcForm object which on creation uses HtmlHelper to write markup to the page. When the using block comes to an end the Dispose method on MvcForm is used to output the closing tag.

Tuesday, 4 September 2012

C# lesser known keywords part 1

This post will give a brief overview of some of the lesser known keywords in C# (as-implicit). I'll cover more in later posts.

as

The as keyword casts the expression on the left to the type on the right if the type matches. If the type on the left is not of the type on the right then null is returned. The following two expressions are equivalent (via MSDN).
expression as Type
expression is Type ? (Type)expression : (Type)null
 

Friday, 17 August 2012

Extension methods

Extension methods are a nice piece of syntactic sugar added to C# version 3.0 as part of .NET framework 3.5. They allow you to add methods to existing types, for example you can add a new method to the type System.String or System.IO.File.

To make an extension method, make the method static and put the this keyword in the front of the type you're extending as the first parameter, like so.
public static class ExtensionMethods
{
    public static void RemoveWhitespace(this string text)
    {
        return text.Replace(" ", "")
                   .Replace("\t", "")
                   .Replace("\n", "");
    }
}
And this is how you would call string.RemoveWhitespace
string text = " a string ";
text.RemoveWhitespace();
// text == "astring" 
Really all that is happening here is you're using a different/nicer syntax to call regular method. Instead of calling some method static string RemoveWhitespace(string text), you're calling it on the instance of string you want to modify.

Extension properties

Extension properties are among the list of features being considered for future versions of C#. Until then we'll need to make do by implementing java-style getters and setters if required.
Sunday, 5 August 2012

Func<> and Action<> basics in C#

If you've been coding in C# for a while you may have noticed the Func<> parameter type presented in several places, particularly LINQ which uses it extensively. You may know how to use it but have you ever thought about what it is exactly and how to go about using it in your own functions?