Category Archives: C#

C# 7 Tuples

C#/.NET has had support for the Tuple class (a reference type) since .NET 4, but with C# 7 tuples now gets some “syntactic sugar” (and a new ValueTuple struct) to make them part of the language.

Previous to C# 7 we’d write code like this

var tuple = new Tuple<string, int>("Four", 4);

var firstItem = tuple.Item1;

Now, in a style more like F#, we can write the following

var tuple = ("Four", 4);

var firstItem = tuple.Item1;

This code makes the creation of tuples slightly simpler but we can also make the use of the “items” within a tuple more readable by using names. So we could rewrite the above in a number of ways, examples of each supplied below

(string name, int number) tuple1 = ("Four", 4);
var tuple2 = (name: "Four", number: 4);
var (name, number) =  ("Four", 4);

var firstItem1 = tuple1.name;
var firstItem2 = tuple2.name;
var firstItem3 = name;

Whilst not quite as nice as F# we also now have something similar to pattern matching on tuples, so for example we might be interested in creating a switch statement based upon the numeric (second item) in the above code, we can write

switch (tuple)
{
   case var t when t.number == 4:
      Console.WriteLine("Found 4");
      break;
}

Again, similar to F# we also can discard items/params using the underscore _, for example

var (_, number) = CreateTuple();

In this example we assume the CreateTuple returns a tuple type with two items. The first is simply ignored (or discarded).

IOException – the process cannot access the file because it is used by another process

I’m using a logging library which is writing to a local log file and I also have a diagnostic tool which allows me to view the log files, but if I try to use File.Open I get the IOException,

“the process cannot access the file because it is used by another process”

this is obviously self-explanatory (and sadly not the first time I’ve had this and had to try and recall the solution).

So to save me searching for it, here the solution which allows me to open a file that’s already opened for writing to by another process

using (var stream = 
   File.Open(currentLogFile, 
      FileMode.Open, 
      FileAccess.Read, 
      FileShare.ReadWrite))
{
   // stream reading code
}

The key to the File.Open line is the FileShare.ReadWrite. We’re interested in opening the file to read but we still need to specify the share flag(s) FileShare.ReadWrite.

How does yield return work in .NET

A while back I had a chat with somebody who seemed very interested in what the IL code for certain C#/.NET language features might look like – whilst it’s something I did have an interest in during the early days of .NET, it’s not something I had looked into since then, so it made me interested to take a look again.

One specific language feature of interest was “what would the IL for yield return look like”.

This is what I found…

Here’s a stupidly simple piece of C# code that we’re going to use. We’ll generate the binary then decompile it and view the IL etc.

public IEnumerable<string> Get()
{
   yield return "A";
}

Using JetBrains dotPeek (ILDASM, Reflector or ILSpy can ofcourse be used to do generate the IL etc.). So the IL created for the above method looks like this

.method public hidebysig instance 
   class [mscorlib]System.Collections.Generic.IEnumerable`1<string> 
      Get() cil managed 
{
   .custom instance void  [mscorlib]System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(class [mscorlib]System.Type) 
   = (
      01 00 1b 54 65 73 74 59 69 65 6c 64 2e 50 72 6f // ...TestYield.Pro
      67 72 61 6d 2b 3c 47 65 74 3e 64 5f 5f 31 00 00 // gram+<Get>d__1..
      )
   // MetadataClassType(TestYield.Program+<Get>d__1)
   .maxstack 8

   IL_0000: ldc.i4.s     -2 // 0xfe
   IL_0002: newobj       instance void TestYield.Program/'<Get>d__1'::.ctor(int32)
   IL_0007: dup          
   IL_0008: ldarg.0      // this
   IL_0009: stfld        class TestYield.Program TestYield.Program/'<Get>d__1'::'<>4__this'
   IL_000e: ret          
} // end of method Program::Get

If we ignore the IteratorStateMachineAttribute and jump straight to the CIL code label IL_0002 it’s probably quite obvious (even if you do not know anything about IL) that this is creating a new instance of some type, which appears to be an inner class (within the Program class) named <Get>d__1. The preceeding ldc.i4.s instruction simply pushes an Int32 value onto the stack, in this instance that’s the value -2.

Note: IteratorStateMachineAttribute expects a Type argument which is the state machine type that’s generated by the compiler.

Now I could display the IL for this new type and we could walk through that, but it’d be much easier viewing some C# equivalent source to get some more readable representation of this. So I got dotPeek to generate the source for this type (from the IL).

First let’s see what changes are made by the compiler to the Get() method we wrote

[IteratorStateMachine(typeof (Program.<Get>d__1))]
public IEnumerable<string> Get()
{
   Program.<Get>d__1 getD1 = new Program.<Get>d__1(-2);
   getD1.<>__this = this;
   return (IEnumerable<string>) getD1;
}

You can now see the newobj in it’s C# form, creating the <Get>d__1 object with a ctor argument of -2 which is assigned as an initial state.

Now let’s look at this lt;Get>d__1 generated code

[CompilerGenerated]
private sealed class <Get>d__1 : 
    IEnumerable<string>, IEnumerable, 
    IEnumerator<string>, IDisposable, 
    IEnumerator
{
   private int <>1__state;
   private string <>2__current;
   private int <>l__initialThreadId;
   public Program <>4__this;

   string IEnumerator<string>.Current
   {
      [DebuggerHidden] get
      {
         return this.<>2__current;
      }
   }

   object IEnumerator.Current
   {
      [DebuggerHidden] get
      {
         return (object) this.<>2__current;
      }
   }

   [DebuggerHidden]
   public <Get>d__1(int <>1__state)
   {
      base..ctor();
      this.<>1__state = param0;
      this.<>l__initialThreadId = Environment.CurrentManagedThreadId;
   }

   [DebuggerHidden]
   void IDisposable.Dispose()
   {
   }

   bool IEnumerator.MoveNext()
   {
      switch (this.<>1__state)
      {
         case 0:
            this.<>1__state = -1;
            this.<>2__current = "A";
            this.<>1__state = 1;
            return true;
          case 1:
            this.<>1__state = -1;
            return false;
          default:
            return false;
      }
   }

   [DebuggerHidden]
   void IEnumerator.Reset()
   {
      throw new NotSupportedException();
   }

   [DebuggerHidden]
   IEnumerator<string> IEnumerable<string>.GetEnumerator()
   {
      Program.<Get>d__1 getD1;
      if (this.<>1__state == -2 && 
          this.<>l__initialThreadId == Environment.CurrentManagedThreadId)
      {
          this.<>1__state = 0;
          getD1 = this;
      }
      else
      {
          getD1 = new Program.<Get>d__1(0);
          getD1.<>4__this = this.<>4__this;
      }
      return (IEnumerator<string>) getD1;
   }

   [DebuggerHidden]
   IEnumerator IEnumerable.GetEnumerator()
   {
      return (IEnumerator) this.System.Collections.Generic.IEnumerable<System.String>.GetEnumerator();
    }
}

As you can see, yield causes the compiler to create enumerable implementation for just that one of code.

Remoting in C# (legacy code)

In another post I looked at remoting using WCF but what were things like before WCF (or what’s an alternative to WCF)? I thought I’d post just the bare bones for getting a really simple service and client up and running.

Note: Microsoft recommends new remoting code uses WCF, so this post is more for understanding legacy code.

Note: I am not going to go into the lifecycle, singletons/single instances etc. here, I’m just going to concentrate on the code to get something working.

The Server

As per my previous post on WCF remoting, we’re going to simply create a console application to act as our server, so go ahead an create one (mine’s named OldRemoteServer) and then add the following

public interface IRemoteService
{
   void Write(string message);
}

into a file of it’s own, then our client can link to it in our client’s Visual Studio solution.

Here’s an implementation for the above

public class RemoteService : MarshalByRefObject, IRemoteService
{
   public void Write(string message)
   {
      Console.WriteLine(message);
   }
}

Note: The implementation needs to be derived from MarshalByRefObject or the class needs to be marked with the Serializable attribute or implement ISerializable which obviously makes sense. We’re solely going to look at MarshalByRefObject implementation for now as these will be passed by reference to the client, whereas the serializable implementations are aimed at passing by value.

Now let’s put some code in the Main method of our Console app.

var channel = new TcpChannel(1002);
ChannelServices.RegisterChannel(channel, false);

RemotingConfiguration.RegisterWellKnownServiceType(
  typeof(RemoteService), 
  "Remote", 
   WellKnownObjectMode.Singleton);

// now let's ensure the console remains open
Console.ReadLine();

In the above code we’re using a Tcp channel with the port number 1002 and in the RegisterWellKnownServiceType, we’re registering the service type (this should be the implementation, not the interface) and supply a name “Remote” for it. In this case I’m also setting it to be a Singleton.

You’ll need to add a reference to System.Runtime.Remoting and the following using clauses

using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

The Client

Create another Console application to simply test this and add the file with the IRemoteService interface.

I’ve simply added it by selecting the client solution, the Add… | Existing Item, locate the file and instead of clicking the Add button select the dropdown to Add As Link. Then if you change the interface it’ll be immediately reflected in the client – ofcourse in a more complex application we’d have the interfaces in their own assembly.

Now to get the client to call the server we simply place the following in the Main method of the Console app.

var obj = (IRemoteService)Activator.GetObject(
   typeof(IRemoteService), 
   "tcp://localhost:1002/Remote");

obj.Write("Hello World");

In the above you’ll see that we use the Activator to get an object and supply the type, then the next line shows we’re using the Tcp channel, port 1002 as set up in the server and the name from the server we game our object “Remote”.

This creates a transparent proxy which we then simply call the interface method Write on.

Configuration

In the above example code I’ve simply hard-coded the configuration details but ofcourse we can create a .config file to instead handle such configurations.

Let’s replace all the server Main method code with the following

RemotingConfiguration.Configure("Server.config", false);

Add an App.config to the project, we’re going to rename it Server.config for this example and ensure that the files’s properties (in Visual Studio) are set to Copy Always (or Copy if newer) to ensure the copy in the bin folders is upto date.

Now here’s the Server.config which recreates the singleton, tcp, port 1002 settings previously handled in code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
  <application>
    <service>
      <wellknown
        type="OldRemoteServer.RemoteService, OldRemoteServer"
        objectUri="Remote"
        mode="Singleton" />
    </service>
    <channels>
      <channel ref="tcp" port="1002"/>
    </channels>
  </application>

  </system.runtime.remoting>
</configuration>

Now if you run the server and then the client, everything should work as before.

Next up, let’s set the client up to use a configuration file…

So we’ll add an App.config file to the client now, but let’s name it Client.config and again set the Visual Studio properties to ensure it’s always copied to the bin folder.

Add the following to the configuration file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <client>
        <wellknown 
          type="OldRemoteServer.RemoteService, OldRemoteServer" 
          url="tcp://localhost:1002/Remote" />
      </client>
    </application>
  </system.runtime.remoting>
</configuration>

It might seem a little odd that we’re declaring the type as the implementation within the server code, but the reason will hopefully become clear.

Add a reference within the client to the RemoteServer (if you have the implementation in a DLL, all the better, we didn’t do that, so I’m referencing the server EXE itself). This now give us access to the implementation of the RemoteService.

Change the client Main method to

RemotingConfiguration.Configure("Client.config", false);

var obj = new RemoteService();
obj.Write("Hello World");

don’t forget to add the using clause

using System.Runtime.Remoting;

This bit might seem a little strange, based upon what we’ve previously done and how we’ve kept a separation of interface and implementation. Aren’t we now simply creating a local instance of the RemoteService, you might ask.

Well try it, run the server and then the client and you’ll find .NET has created a transparent proxy for us and calls to the RemoteService will in fact go to the server.

Whilst this makes things very easy, I must admit I prefer to not reference the implementation of the RemoteService.

What about named pipes?

Let’s now look at the changes to use the IPC protocol (for implementing named pipes) in .NET remoting. I’ll just briefly cover the changes required to implement this.

To start with let’s rewrite the server and client in code. So first the Main method in the server should now look like

var channel = new IpcChannel("ipcname");
ChannelServices.RegisterChannel(channel, false);

RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteService),
   "Remote",
   WellKnownObjectMode.Singleton);

Console.ReadLine();

So the only real difference from the Tcp implementation is the use of an IpcChannel and the name supplied instead of a port.

The client then looks like this

var obj = (IRemoteService)Activator.GetObject(
   typeof(IRemoteService), 
   "ipc://ipcname/Remote");

obj.Write("Hello World");

Simple enough.

Now let’s change the code to use a configuration file.

The server Main method should now look like this

RemotingConfiguration.Configure("Server.config", false);
Console.ReadLine();

and the Server.config should look like this

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
  <application>
    <service>
      <wellknown
        type="OldRemoteServer.RemoteService, OldRemoteServer"
        objectUri="Remote"
        mode="Singleton" />
    </service>
    <channels>
      <channel ref="ipc" portName="ipcname"/>
    </channels>
  </application>

  </system.runtime.remoting>
</configuration>

The client code should be

RemotingConfiguration.Configure("Client.config", false);
var obj = new RemoteService();
obj.Write("Hello World");

and it’s Client.config should look like this

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <client>
        <wellknown 
          type="OldRemoteServer.RemoteService, OldRemoteServer" 
          url="ipc://ipcname/Remote" />
      </client>
    </application>
  </system.runtime.remoting>
</configuration>

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