Category Archives: C#

Debugger Attributes

There’s several debugging types of attributes I use fairly regularily, such as DebuggerStepThrough and DebuggerDisplay, but I decided to take a look at some of the other, similar, attributes to see if I was missing anything, here’s what I found out.

Introduction

At the time of writing these are the debugging attributes I found

  • DebuggerStepThrough
  • DebuggerDisplay
  • DebuggerNonUserCode
  • DebuggerHidden
  • DebuggerBrowsable
  • DebuggerTypeProxy
  • DebuggerStepperBoundary

Before I get into the specific attributes, I will be listing the attribute targets that the attribute may be applied to, when it says an attribute may be set on a method, this also includes the setter/getter (methods) on a property. But not the property itself, this requires the AttributeTargets.Property target to be set.

DebuggerStepThrough

References

DebuggerStepThroughAttribute Class

Usage

  • Class
  • Struct
  • Constructor
  • Method

Synopsis

Let’s start with the one I used a lot in the past (on simple properties, i.e. equivalent of auto-properties). Placing a DebuggerStepThrough on any of the usage targets, will inform the debugger (in Visual Studio, not tested in Xamarin Studio as yet) to simply step through (or in debugging terms, step over) the code. In other words the debugger will not enter a method call.

This is especially useful for situations where, maybe you have simple code, such as properties which just return or set a value and this will save you stepping into this property setters or getters during a debugging session.

Example

public class MyClass
{
   private int counter;

   [DebuggerStepThrough]
   public int Increment()
   {
      return counter++;
   }
}

As stated in the usage, you can also apply this to the class itself to stop the debugger stepping into any code in the class. Useful if the class is full of methods etc. which you don’t need to step into.

DebuggerDisplay

Next up, is the DebuggerDisplayAttribute.

References
DebuggerDisplayAttribute Class

Usage

  • Assembly
  • Class
  • Struct
  • Enum
  • Property
  • Field
  • Delegate

Synopsis

In situations where you’re debugging and you place the mouse pointer over the an instance of MyClass (as defined previously) you’ll see the popup say something like

{MatrixTests.MyClass}

next to the variable name. This is fine if all you want is the type name or if you want to drill into the instance to view fields or properties but if you’ve got many fields or properties, it might be nicer if the important one(s) are displayed instead of the type name.

Before we delve into DebuggerDisplay, if your class implements a ToString override method then this will normally be displayed by the debugger. If you’re using this for something else, then it will not fulfill the requirements for displaying something different when the instance is hovered over. But if this ToString has everything you need then there’s no need for a DebuggerDisplay attribute.

Example

Let’s start by seeing the ToString and DebuggerDisplay that would be equivalent

public override string ToString()
{
   return $"Counter = {counter}";
}

// equivalent to 

[DebuggerDisplay("Counter = {counter}")]
public class MyClass
{
   // code
}

Both of the above will show debugger popup of “Counter = 0” (obviously 0 is replaced with the current counter value).

As you can see within the DebuggerDisplayAttribute, we can include text and properties/fields we just need to enclose them in {}. We can also use methods, within the DebuggerDisplay. Let’s assume we have a private method which creates the debugger output

[DebuggerDisplay("{DebuggerString()}")]
public class MyClass
{
   private string DebuggerString()
   {
      return $"Counter = {counter}";
   }
   // other code
}

As stated previously these all show a debugger display of “Counter = 0” – they also display quotes around the text. We can remove these by specifying nq (nq == no quotes), as per

[DebuggerDisplay("{DebuggerString(), nq}")]

So now the output display is Counter = 0 i.e. without quotes.

You can, ofcourse, extend format to display more fields/properties as per C# 6.0 string interpolation. i.e. if we have a matrix class with two properties, Rows and Columns and want to display these in the debugger display we can use

[DebuggerDisplay("Rows = {Rows}, Columns = {Columns}")]

We can also extend this syntax to use basic expressions, for example

[DebuggerDisplay("Counter = {counter + 10}")]

the above code will evaluate the counter field and then add 10 (as I’m sure you guessed).

Gotcha’s

Just remember that whatever you place in the DebuggerDisplay will be executed when you view it. So if you’re calling a remote service or database, be ready for the performance hit etc.

DebuggerNonUserCode

References

DebuggerNonUserCodeAttribute Class
Using the DebuggerNonUserCode Attribute in Visual Studio 2015
Change Debugger behavior with Attributes

Usage

  • Class
  • Struct
  • Constructor
  • Method
  • Property

Synopsis

This is very similar to DebuggerStepThrough, but as you can see from the usage, also allows us to apply this attribute to a property as a whole.

Examples

Used in the same way as DebuggerStepThrough, see those examples.

DebuggerHidden

References

DebuggerHiddenAttribute Class
Using the DebuggerNonUserCode Attribute in Visual Studio 2015
Change Debugger behavior with Attributes

Usage

  • Constructor
  • Method
  • Property

Synopsis

This is very similar to DebuggerStepThrough and DebuggerNonUserCode, but as you can see from the usage it’s somewhat restricted on what it can be applied to.

Examples

Used in the same way as DebuggerStepThrough, see those examples.

DebuggerBrowsable

References

DebuggerBrowsableAttribute Class

Usage

  • Property
  • Field

Synopsis

If you are viewing an instance of the MyClass (shown previously) within the popup debug window (displayed when you hover over the instance variable during a Visual Studio debugging session), you will see a + sign to the left of the class, meaning you can view the fields/properties in this class, but in some situations you might want to reduce the fields/properties (or what might be seen as noise). This is especially useful in situations where maybe you have lots of fields or properties which are maybe of limited usefulness in a debugging scenario, or maybe pre auto properties, you might wish to “hide” all fields. Then simply mark the field or property with

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int counter;

Now when you view the instance of MyClass, no + will appear as I’ve stipulated never display this field as browseable.

The other options for DebuggerBrowsableState are

  • DebuggerBrowsableState.Collapsed
  • DebuggerBrowsableState.RootHidden

as per Microsoft documentation…

Collapsed shows the element as collapsed whilst RootHidden does not display the root element; display the child elements if the element is a collection of array items.

Examples

// never show the field in the debugger popup
// wtahc or auto windows
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int counter;

Basically RootHidden used on an array property (for example)

public int[] Counters
{
   //
}

will not display Counters, but will displace the array of elements.

DebuggerTypeProxy

References

Using DebuggerTypeProxy Attribute

Usage

  • Assembly
  • Class
  • Struct

Synopsis

When we looked at the DebuggerDisplay we found we could reference fields/properties within the class and even use a limited set of expressions. But in some scenarios, such as the one where we added a DebuggerString to the class, it might be preferable to extract the debugger methods/properties etc. to ensure the readability and maintainability of the original class.

Examples

Let’s start by changing the MyClass code to this

[DebuggerTypeProxy(typeof(MyClassDebuggerProxy))]
public class MyClass
{
   private int counter;

   public int Counter => counter;

   public int Increment()
   {
      return counter++;
   }
}

I’ve added a property Counter, to allow us to use the counter in our proxy

Now create a simple proxy that looks like this

public class MyClassDebuggerProxy
{
}

If you now try to view the fields on an instance of MyClass the debugger will use the MyClassDebuggerProxy and in this instance there are no fields/properties and therefore nothing will be displayed (well they will if you expand Raw View but not at the top level in the debugger). So in this form, it’s a simple way to hide everything from the debugger – if that is required. Let’s be honest that’s not usually the intention, so let’s add some properties to the proxy and use the MyClass.Counter property.

public class MyClassDebuggerProxy
{
   private MyClass _instance;

   public MyClassDebuggerProxy(MyClass instance)
   {
      _instance = instance;
   }

   public int DebuggerCounter {  get { return _instance.Counter; } }
}

Now when you debug an instance of MyClass, the debugger will display the property DebuggerCounter from the proxy class. The _instance field will not be displayed. This example is a little pointless, but unlike the limited expression capability of DebuggerDisplay, the full capabilities of .NET can be used to add more data to the debugger, or change debugger displayed data.

Note: If you want to display something other than the type for the instance of MyClass, then you’ll still need to apply a DebuggerDisplay attribute to the MyClass object, not to the proxy as this will be ignored.

DebuggerStepperBoundary

References

DebuggerStepperBoundaryAttribute Class

Usage

  • Constructor
  • Method

Synopsis

This is a slightly odd concept (well it is to me at the moment). Using this attribute on a method (say our Increment method in MyClass) will in essence tell the debugger to switch from stepping mode to run mode. In other words, if you have a breakpoint on a call to myClass.Increment then press F10 or F11 (to step over or step in to the Increment method) the debugger will see the DebuggerStepperBoundary and instead do the equivalent of F5 (or run). From this perspective the use of such an attribute seems fairly limited, however the Microsoft documentation (shown in the references above) states…

“When context switches are made on a thread, the next user-supplied code module stepped into may not relate to the code that was in the process of being debugged. To avoid this debugging experience, use the DebuggerStepperBoundaryAttribute to escape from stepping through code to running code.”

Covariance and contravariance

Before we begin, let’s define the simplest of classes/hierarchies for our test types…

The following will be used in the subsequent examples

class Base { }
class Derived : Base { }

With that out of the way, let’s look at what covariance and contravariance mean in the context of a programming language (in this case C#).

The covariant and contravariant described, below, can be used on interfaces or delegates only.

Invariant

Actually we’re not going straight into covariance and contravariance, let’s instead look at what an invariant generic type might look like (as we’ll be building on this in the examples). Invariant is what our “normal” generics or delegates might look like.

Here’s a fairly standard use of a generic

interface IProcessor<T> 
{
}

class Processor<T> : IProcessor<T>
{        
}

If we try to convert an IProcessor<Derived> to an IProcessor<Base> or vice versa, we’ll get a compile time error, i.e. here’s the code that we might be hoping to write

Now if we wanted to do the following

IProcessor<Derived> d = new Processor<Derived>();
IProcessor<Base> b = d;

// or

IProcessor<Base> b = new Processor<Base>();
IProcessor<Derived> d = b;

So, in the above we’re creating a Processor with the generic type Derived (in the first instance) and we might have a method that expects an IProcessor. In our example we simulate this with the assignment of d to b. This will fail to compile. Likewise the opposite is where we try to assign a IProcessor to an IProcessor, again this will fail to compile. At this point the IProcessor/Processor are invariant.

Obviously with the derivation of Base/Derived, this would probably be seen as a valid conversion, but not for invariant types.

With this in mind let’s explore covariance and contravariance.

Covariance

Covariance is defined as enabling us to “use a more derived type than originally specified” or to put it another way. If we have an IList<Derived> we can assign this to a variable of type IList<Base>.

Using the code

IProcessor<Derived> d = new Processor<Derived>();
IProcessor<Base> b = d;

we’ve already established, this will not compile. If we add the out keyword to the interface though, this will fix the issue and make the Processor covariant.

Here’s the changes we need to make

interface IProcessor<out T> 
{
}

No changes need to be made on the implementation. Now our assignment from a derived type to a base type will succeed.

Contravariance

As you might expect, if covariance allows us to assign a derived type to a base type, contravariance allows us to “use a more generic (less derived) type than originally specified”.

In other words, what if we wanted to do something like

IProcessor<Base> b = new Processor<Base>();
IProcessor<Derived> d = b;

Ignore the fact that b cannot possibly be the same type in this example (i.e. Derived)

Again, you may have guessed, if we used an out keyword for covariance and contravariance is (sort of) the opposite, then the opposite of out will be the in keyword, hence we change the interface only to

interface IProcessor<in T>
{
}

Now our code will compile.

What if we want to extend a covariant/contravariant interface?

As noted, the in/out keywords are used on interfaces or delegates, if we wanted to extend an interface that supports one of these keywords, then we would apply the keyword to the extended interfaces, i.e.

interface IProcessor<out T>
{
}

interface IExtendedProcessor<out T> : IProcessor<T>
{
}

obviously we must keep the interface the same variance as the base interface (or not mark it as in/out. We apply the keyword as above.

References

Covariance and Contravariance in GenericsCovariance and Contravariance FAQ
in (Generic Modifier) (C# Reference)
out (Generic Modifier) (C# Reference)

Fun with Expression objects

Expressions are very useful in many situation. For example, you have a method which you pass a lambda expression to and the method can then determine the name of the property the lambda is using or the method name etc. Or maybe you’ve used them in the past in view model implementations pre-nameof. They’re also used a lot in mocking frameworks, to make the arrange steps nice and terse.

For example

Expressions.NameOf(x => x.Property);

In the above example the lambda expression is the x => x.Property and the NameOf method determines the name of the property, i.e. it returns the string “Property” in this case.

Note: This example is a replacement for the nameof operator for pre C# 6 code bases.

Let’s look at some implementations of such expression code.

InstanceOf

So you have code in the format

Expressions.InstanceOf(() => s.Clone());

In this example Expressions is a static class and InstanceOf should extract the instance s from the expression s.Clone(). Obviously we might also need to use the same code of a property, i.e. find the instance of the object with the property.

public static object InstanceOf<TRet>(Expression<Func<TRet>> funcExpression)
{
   var method = funcExpression.Body as MethodCallExpression;
   // if not a methood, try to get the body (possibly it's a property)
   var memberExpression = method == null ? 
      funcExpression.Body as MemberExpression : 
      method.Object as MemberExpression;

   if(memberExpression == null)
      throw new Exception("Unable to determine expression type, expected () => vm.Property or () => vm.DoSomething()");

   // find top level member expression
   while (memberExpression.Expression is MemberExpression)
      memberExpression = (MemberExpression)memberExpression.Expression;

   var constantExpression = memberExpression.Expression as ConstantExpression;
   if (constantExpression == null)
      throw new Exception("Cannot determine constant expression");

   var fieldInfo = memberExpression.Member as FieldInfo;
   if (fieldInfo == null)
      throw new Exception("Cannot determine fieldinfo object");

   return fieldInfo.GetValue(constantExpression.Value);
}

NameOf

As this was mentioned earlier, let’s look at the code for a simple nameof replacement using Expressions. This implementation only works with properties

public static string NameOf<T>(Expression<Func<T>> propertyExpression) 
{
   if (propertyExpression == null)
      throw new ArgumentNullException("propertyExpression");

   MemberExpression property = null;

   // it's possible to end up with conversions, as the expressions are trying 
   // to convert to the same underlying type
   if (propertyExpression.Body.NodeType == ExpressionType.Convert)
   {
      var convert = propertyExpression.Body as UnaryExpression;
      if (convert != null)
      {
         property = convert.Operand as MemberExpression;
      }
   }

   if (property == null)
   {
      property = propertyExpression.Body as MemberExpression;
   }
   if (property == null)
      throw new Exception(
         "propertyExpression cannot be null and should be passed in the format x => x.PropertyName");

   return property.Member.Name;
}

Automating Excel (some basics)

Here’s some basic for automating Excel from C#.

Make sure you dereference your Excel COM objects

Actually I’m going to start with a word of caution. When interacting with Excel you need to ensure that you dereference any Excel objects after use or you’ll find Excel remains in memory when you probably thought it had been closed.

To correctly deal with Excel’s COM objects the best thing to do is store each object in a variable and when you’ve finished with it, make sure you set that variable to null. Accessing some Excel objects using simply dot notation such as

application.Workbooks[0].Sheets[1];

will result in COM objects being created but without your application having a reference to them they’ll remain referenced long after you expect.

Instead do things like

var workbooks = application.Workbooks[0];
var workSheet = workbooks.Sheets[1];

If in doubt, check via Task Manager to see if your instance of Excel has been closed.

Starting Excel

var application = new Excel.Application();
var workbook = application.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = workbook.Sheets[1];

application.Visible = true;

Setting Cell data

worksheet.Cells[row, column++] = 
    cell.Value != null ? 
       cell.Value.ToString() : 
       String.Empty;

Grouping a range

Excel.Range range = worksheet.Rows[String.Format("{0}:{1}", row, row + children)];
range.OutlineLevel = indent;
range.Group(Missing.Value, Missing.Value, Missing.Value, Missing.Value);

Change the background colour

worksheet.Rows[row].Interior.Color = Excel.XlRgbColor.rgbRed;

Change the background colour from a Color object

We can use the built-in colour conversion code, which from WPF would mean converting to a System.Drawing.Color, as per this

																			System.Drawing.Color clr = System.Drawing.Color.FromArgb(solid.Color.A, solid.Color.R, solid.Color.G, solid.Color.B);

Now we can use this as follows

worksheet.Rows[row].Interior.Color = ColorTranslator.ToOle(clr);

or we can do this ourselves using

int clr = solid.Color.R | solid.Color.G << 8 | solid.Color.B << 16;									worksheet.Rows[row].Interior.Color = clr;

Changing the foreground colour

int clr = solid.Color.R | solid.Color.G << 8 | solid.Color.B << 16;									worksheet.Rows[row].Font.Color = clr;

References

https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.aspx

Using ConfigureAwait

By default code after an await continues on the calling thread (i.e. the thread prior to the await keyword). In many cases this is what we want to happen. Remember async methods are not necessarily run on another task/thread, but in those instances where we know that they are truly asynchronous, we might actually want our code after the await to also run in the same context (i.e. on the same background thread of the async method).

So, for the sake of argument we’ll assume we’re awaiting a Task which we know is run on a background thread. Upon completion we intend to process some results from this Task, also on a background thread. Now obviously we could do something like

private async Task Process()
{
   var results = await SomeBackgroundThreadMethod();
   await Task.Run(() => ProcessOnBackgroundThread(results);
}

We can see that if SomeBackgroundThreadMethod runs on a background thread then after the await we continue on the calling thread before again spinning up another Task to run our processing code. So we’re potentially using two background threads when in reality, if we know SomeBackgroundThreadMethod actually is running on a background thread then we could simply continue to process on this same thread.

Okay, so this is a little contrived because, as you know, the SomeBackgroundThreadMethod would itself return a Task and we could simply ContinueWith on this Task. But an alternative to ContinueWith is to call ConfigureAwait on the SomeBackgroundThreadMethod Task, such as

private async Task Process()
{
   var results = await SomeBackgroundThreadMethod().ConfigureAwait(false);
   ProcessOnBackgroundThread(results)
}

Gotchas?

  • Now the code which uses ConfigureAwait seems quite obvious, but ConfigureAwait does not magically create a Task or background thread if none existed on the return from SomeBackgroundThreadMethod. For example if SomeBackgroundThreadMethod simply returns a TaskCompletionSource, ConfigureAwait would simply end up being on the calling thread.
  • ConfigureAwait only affects code following it and within the scope of the method using it, hence in the above code once we exit the Process method all async/await calls will return to their default behaviour, it’s only code within the Process method after the await which continues on the same thread as SomeBackgroundThreadMethod.

References
Task.ConfigureAwait

C# 6 features

A look at some of the new C# 6 features (not in any particular order).

The Null-conditional operator

Finally we have a way to reduce the usual

if(PropertyChanged != null)
   PropertyChanged(sender, propertyName);

to something a little more succinct

PropertyChanged?.Invoke(sender, propertyName);

Read-only auto properties

In the past we’d have to supply a private setter for read only properties but now C# 6 allows us to do away with the setter and we can either assign a value to a property within the constructor or via a functional like syntax, i.e.

public class MyPoint
{
   public MyPoint()
   {
      // assign with the ctor
      Y = 10;
   }

   // assign the initial value via the initializers
   public int X { get; } = 8;
   public int Y { get; }
}

Using static members

We can now “open” up static class methods and enums using the

using static System.Math;

// Now instead of Math.Sqrt we can use
Sqrt(10);

String interpolation

Finally we have something similar to PHP (if I recall my PHP from so many years back) for embedding values into a string. So for example we might normally write String.Format like this

var s = String.Format("({0}, {1})", X, Y);

Now we can instead write

var s = $"({X}, {Y})";

Expression-bodied methods

A move towards the way F# might write a single line method we can now simplify “simple” methods such as

public override string ToString()
{
   return String.Format("({0}, {1})", X, Y);
}

can now be written as

public override string ToString() => String.Format("({0}, {1})", X, Y);

// or using the previously defined string interpolation
public override string ToString() => $"({X}, {Y})";

The nameof expression

Another improvement to remove aspects of magic strings, we now have the nameof expression. So for example we might have something like this

public void DoSomething(string someArgument)
{
   if(someArgument == null)
      throw new ArgumentNullException(nameof(someArgument));

   // do something useful
}

Now if we change the someArgument variable name to something else then the nameof expression will correctly pass the new name of the argument to the ArgumentNullException.

However nameof is not constrained to just argument in a method, we can apply nameof to a class type, or a method for example.

References

What’s new in C# 6

Populating random data

I was working on a small utility which generates XML based upon a given class (which is already XML serializable). I wanted to generate random data just so I could see how the end XML looked in case I needed to tweak the XSD.

Source for the utility is available on AutoGenXml.

I figured somebody must have already approached such a problem, and thankfully I was right. There are a few solutions for populating object data. I ended up trying out two different libraries, AutoFixture and NBuilder.

Disclaimer: I have literally only just started using these libraries, so I’ve yet to find all the good and/or bad points of each library.

Let’s take a real quick look at what these libraries can do.

Test object

Let’s start out by defining an object hierarchy to test this two libraries out on. Mine looks like this

public class Album
{
   public string Title { get; set; }
   public string RecordLabel { get; set; }
   public Artist Artist { get; set; }
   public string Genre { get; set; }
}

public class Artist
{
   public string Name { get; set; }
   public BandMember[] Band { get; set; }
}

public class BandMember
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Talent { get; set; }
}

AutoFixture

AutoFixture source can be found on AutoFixture.

We can create objects with AutoFixture (hence using it as the factory for our objects) and it returns a populated object hierarchy.

Let’s look at the code (it’s pretty simple)

var fixture = new Fixture();
var album = fixture.Create<Album>();

The album will now have data in all fields and the Artist and BandMember properties are also created and data supplied.

Whilst it’d obviously be easy enough for us to create an object multiple times if we wanted a list of Albums but AutoFixture also supplies this code to do the same thing

var fixture = new Fixture {RepeatCount = 10};
var albums = fixture.
                 Repeat(fixture.Create<Album>).
                 ToArray();

NBuilder

NBuilder source can be found on NBuilder.

NBuilder also supplies a factory pattern for both creating our objects and populating the object.

Here’s the code

var album = Builder<Album>
               .CreateNew()
               .Build();

NBuilder uses a fluent style interface and offers options for creating multiple items (i.e. an IList<> of objects). There’s also a mechanism for us to intercept the object population step and supply our own data. So whilst in the usage shown above, we don’t have the object heriarchy created, we can create this ourselves fairly easily using

var albums = Builder<Album>
   .CreateListOfSize(10)
   .All()
      .With(a => a.Artist = Builder<Artist>.CreateNew()
         .With(b => b.Band = Builder<BandMember>
                    .CreateListOfSize(3)
                       .Build().ToArray())
	.Build())
   .Build();

References

This is a great post on using NBuilder with Faker which allows us to populate the objects with more realistic data than the default process.

Compiling C# code at runtime

Occasionally we might come across a problem which lends itself well to the idea of C# code being compiled at runtime, maybe we’ve created some script like plug-in or in my case I wanted to generate sample XML data from xsd.exe generated classes at runtime.

We can use the CSharpCodeProvider to do exactly this, it can compile some code, create an assembly (in my case in-memory) and then allow us to instantiate the code within that assembly. Let’s jump straight into some code and then we’ll look at how the code works

var param = new CompilerParameters
{
   GenerateExecutable = false,
   IncludeDebugInformation = false,
   GenerateInMemory = true
};
param.ReferencedAssemblies.Add("System.dll");
param.ReferencedAssemblies.Add("System.Xml.dll");
param.ReferencedAssemblies.Add("System.Data.dll");
param.ReferencedAssemblies.Add("System.Core.dll");
param.ReferencedAssemblies.Add("System.Xml.Linq.dll");

var codeProvider = new CSharpCodeProvider();
var results = codeProvider.CompileAssemblyFromFile(param, filename);

if (results.Errors.HasErrors)
{
   foreach (var error in results.Errors)
   {
      Console.WriteLine(error);
   }
}
else
{
   object o = results.
               CompiledAssembly.
               CreateInstance(typeName);
}

In the code above, we’re assuming that the source code we want to compile exists in a seperate C# source code file stored in the variable filename.

Firstly we create the CompilerParameters. I don’t want an executable to be generated and debug information will be of little use to me. I’m going to create the resultant assembly in memory as we’re not intending to write this to disc.

Next up we need to tell the compiler what assemblies will be required, ofcourse this might be best supplied in some alternate way, such as the script itself could be parsed or we might have another file with the assemblies listed, but for my purposes I’ll just list the “standard” assemblies.

We create a CSharpCodeProvider (as we’re working in C#) and passing the compiler parameters and the source code filename we get the code provider to compile the code. If any errors occur we simply list them (in this example, to the console).

Assuming all compiles we use the CompiledAssembly and create an instance of the type we’re interested in. In my example I supplied the typeName (i.e. class name) in the command line arguments to the application which uses obviously allows this code to be a little more flexible.

Once we’ve got the instance of the type we can obviously start interacting with it.

Invoking with generics using reflection

Sometimes we need to run methods or create types with generic parameters at runtime. For example, situation where the type is not known at compiler time but the method(s) we want to use expect the generic parameter to be supplied.

Let’s take a look at the syntax of various scenarios and you’ll get the idea.

Calling an instance method

So let’s assume we have some code like this

public class Runner
{
   public T Create<T>()
   {
      // do something
      return default(T);
   }
}

and we want to invoke this at runtime with an “unknown” (i.e. discovered at runtime) type. We can write something like this

object unknown = CreateType(); // generates some type at runtime

var runner = new Runner();

typeof (Runner).
   GetMethod("Create").
   MakeGenericMethod(unknown.GetType()).
   Invoke(runner, null);

This code would also work if the Create method was a static.

Note: we can ofcourse use typeof(Runner) or runner.GetType() in the above depending upon your preference or use.

Next up, let’s look at the same code but where we need to also pass the method a generic parameter.

public class Runner
{
   public T Create<T>(T type)
   {
      // do something
      return type;
   }
}

So the only real difference here is that we also need to pass the type into the method, a simple addition of the parameters to the invoke will allow this to work, here’s the code

object unknown = CreateType(); // generates some type at runtime

var runner = new Runner();

typeof(Runner).
   GetMethod("Create").
   MakeGenericMethod(unknown.GetType()).
   Invoke(runner, new []{ unknown });

Calling methods on a static class or extension methods

As you will know, extension methods are really just static classes with syntactic sugar to allow them to appear like instance methods, so the procedure for invoking them is the same as the normal static classed, but we’ll cover examples here all the same.

Let’s first look at a static class

public static class Runner
{
   public static T Create<T>()
   {
      // do something
      return default(T);
   }
}

The only real difference to the code for the instance method on a non-static class is that we do not pass a instance to the first parameter of the invoke method, like this

object unknown = CreateType(); // generates some type at runtime

typeof(Runner).
   GetMethod("Create").
   MakeGenericMethod(unknown.GetType()).
   Invoke(null, null);

As extension methods expect a “this” argument, they’re no different to the above code, expect that we need to ensure the first argument is the instance of an object

public static class Runner
{
   public static T Create<T>(this DoSomething doSomething)
   {
      // do something
      return default(T);
   }
}

public class DoSomething
{		
}

So this assumes Create is an extension method for the class, DoSomething. To invoke this Create method we can simply write

object unknown = CreateType(); // generates some type at runtime

var doSomething = new DoSomething();

typeof(Runner).
   GetMethod("Create").
   MakeGenericMethod(unknown.GetType()).
   Invoke(null, new object[]{ doSomething });

Classes with generic parameters

So now let’s move the generic parameter onto the class itself. We’ll begin by looking at static classes

public static class Runner<T>
{
   public static T Create()
   {
      // do something
      return default(T);
   }
}

So now we need to make the generic on the type not the method. We get this

typeof(Runner<>).
   MakeGenericType(unknown.GetType()).
   GetMethod("Create").
   Invoke(null, null);

Notice how the MakeGenericType is used to generate our generic class and the syntax of the typeof.

Obviously we might wish to create non-static classes with generic parameters as well, something like this

public class Runner<T>
{
   public T Create()
   {
      // do something
      return default(T);
   }
}

ofcourse we can’t simply create an instance to this class and use the same techniques of previous because the type of the generic parameter is not known, so we need to create an instance of this class via reflection then invoke the method – this can be accomplished with

var genericType = typeof (Runner<>).
	MakeGenericType(unknown.GetType());

var runner = Activator.CreateInstance(genericType);

genericType
	.GetMethod("Create").
	Invoke(runner, null);

In the above we need to use the genericType twice, so we store it in a local variable. The first time we use it is with Activator.CreateInstance this creates an instance of the class with a generic parameter. Next we use the same type but with the GetMethod call and ofcourse pass the instance variable into Invoke.

What about when we have more than one generic parameter

So what if we had something like this

public class Runner<T1, T2>
{
   public T1 Create()
   {
      var t2 = default(T2);
      // do something
      return default(T1);
   }
}

Obviously this is assuming T2 actually does something of use in our code.

All of the previous sample code will work, the difference is that we declare the typeof(Runner<>) as typeof(Runner<,>) and need to pass the extra parameters in the MakeGenericType method, for example

var genericType = typeof (Runner<,>).
   MakeGenericType(unknown1.GetType(), unknown2.GetType());

var runner = Activator.CreateInstance(genericType);

genericType
   .GetMethod("Create").
   Invoke(runner, null);

Increasing the maximum number of connections with maxconnection

By default when calling webservices etc. we’re limited to 2 maximum connections at a time in an application, so it doesn’t matter if you (for example) create multiple background threads to run webservice calls as you’ll still be limited to two connections.

We can change this using the App.config for our application and adding the following

<system.net>
   <connectionManagement>
      <add address="*" maxconnection="20"/>
   </connectionManagement>
</system.net>

See ConnectionManagementElement.MaxConnection Property

Note: The maxconnection does not apply to local web service calls