void Nish(char* szBlog);

Nish’s thoughts on MFC, C++/CLI and .NET

void Nish(char* szBlog); header image 1

Undocumented compiler error CS0226

February 28th, 2010 · No Comments

This one’s an obvious error really – but it’s still undocumented, and thus qualifies for a blog entry. I guess once __arglist was dropped from the standard documentation, all its associated error messages were dropped too.

Compiler Error CS0226

Error Message

An __arglist expression may only appear inside of a call or new expression

Example

The following sample generates CS0226

// error CS0226
__arglist("apples", "pears");

Expected usage
static void Foo(Object obj, __arglist)
{
    Console.WriteLine("First arg : {0}", obj);

    ArgIterator iterator = new ArgIterator(__arglist);
    for (int i = iterator.GetRemainingCount(); i > 0; i--)
    {
        Console.WriteLine(TypedReference.ToObject(iterator.GetNextArg()));
    }
}

. . .

Foo(x, __arglist("apples", "pears"));

→ No CommentsTags: C#/.NET · VC++ 2010

C++/CLI bug : Operator overloading in an interface

February 27th, 2010 · 1 Comment

There was a very interesting thread on Code Project’s C++/CLI forum last week. Here’s the link to the thread :

The gist of the post is that the C++/CLI compiler was not recognizing an overloaded unary operator defined in an interface while it could do so when the interface was changed to a base class.

Here’s some example code that reproduces the problem :

 interface class Base
 {
 public:
  static int operator * (Base^) { return 99; }
  static int operator + (Base^) { return 99; }
 };

 ref class Derived : Base
 {
 }; 

  static void Foo()
  {
    Derived^ d = gcnew Derived();

    int x = *d;
    int y = +d; 

Both those lines will not compile. In the case of the * operator you get a confusing error because the compiler assumes you are trying to dereference the handle.

Error 1 error C2440: 'initializing' : cannot convert from
    'Test::Derived' to 'int'
Error 2 error C2675: unary '+' : 'Test::Derived ^' does not define this
    operator or a conversion to a type acceptable to the predefined
    operator

Changing Base from an interface class to a ref class works fine. I believe this is a compiler bug because the ECMA language specification says this in section 25.2 Interface members:

“An interface definition can declare zero or more members. The members of an interface shall be static data members, instance or static functions, a static constructor, instance or static properties, instance or static events, operator functions, or nested types of any kind. An interface shall not contain instance data members, instance constructors, or a finalizer.”

The workaround right now is to do this :

int x = Base::operator *(d);
int y = Base::operator +(d);
Affected versions:

This bug exists in VS 2008 as well as in VS 2010 RC.

→ 1 CommentTags: C++/CLI · VC++ 2010

Undocumented compiler error CS0224

February 26th, 2010 · No Comments

A fellow CPian leppie had posted about an undocumented C# error he got (error CS0224) and asked if anyone could reproduce the error (back in Dec 2009). For fun I played with the compiler and managed to reproduce the error. That gave me the idea of blogging about this and other such undocumented errors. Of course the moment I blog about it, it ceases to become undocumented by definition. Also by undocumented, I mean undocumented on MSDN. It may have been blogged on or written about elsewhere, though I do intend to use Google and Bing to try and make sure it’s not a commonly known error. I start off with leppie’s error of CS0224.

As of today (Feb 26, 2010) VS 2008’s MSDN documentation jumps from CS0221 to CS0225, and VS 2010’s MSDN documentation jumps from CS0201 to CS0229. I don’t know why VS 2010 decided to drop those extra error codes, but then this is the RC documentation, and maybe the RTM version will add back those that were documented in VS2008. Anyway enough with the talk and on to the error.

Compiler Error CS0224

Error Message

A method with vararg cannot be generic, be in a generic type, or have a parameter array

Example

The following sample generates CS0224

// error CS0224
static void Foo<T>(T t, __arglist) { }

Correct way

You could rewrite the method in one of the following two ways to get the equivalent functionality :

static void Foo<T>(T t, params object[] args) { }

or

static void Foo(Object obj, __arglist)  { }

→ No CommentsTags: C#/.NET

Rewriting a WCF service in WWS

July 25th, 2009 · 4 Comments

In my last blog entry I had shown a WWS native client connecting to a WCF service. In this one I’ll talk about how the WCF service can be converted into an equivalent WWS service. Connecting clients (whether WWS, WCF, or other) would continue to behave the same. I am going to use the same c/h files that wsutil generated from the wsdl file. There is a function signature generated for us to match the service contract methods. In our case there’s just one – WSHttpBinding_IStringService_ReverseCallback. So the first thing is to add a method that matches this signature, and this will reverse a string just like the WCF service (except we write it in C or C++).

HRESULT CALLBACK Reverse(
	__in const WS_OPERATION_CONTEXT* context,
	__in WCHAR* s,
	__out  WCHAR** reverse,
	__in_opt const WS_ASYNC_CONTEXT* asyncContext,
	__in_opt WS_ERROR* error)
{
	WS_HEAP* heap = NULL;

	HRESULT hr = WsGetOperationContextProperty(
		context,
		WS_OPERATION_CONTEXT_PROPERTY_HEAP,
		&heap,
		sizeof(heap),
		error);

	if (FAILED(hr))
	{
		return hr;
	}

	hr = WsAlloc(
           heap,
           sizeof(WCHAR) * (wcslen(s) + 1),
           (void**)reverse,
           error);

	if (FAILED(hr))
	{
		return hr;
	}

	wcscpy(*reverse, s);
	wcsrev(*reverse);

	return ERROR_SUCCESS;
}

I first use WsGetOperationContextProperty to get the heap and then use WsAlloc to allocate memory for the reversed string on this heap. We do not ever allocate memory using standard memory allocation mechanisms unless it’s memory we will have the option to delete/free when we are done using it. Instead we use the WWS heap which frees us from worrying about memory leaks – the memory will be released when the heap is reset or freed.

Now let’s get to creating the service. Again, I will not show the error handling code (to save space) but every HRESULT return value must be checked for success before proceeding further. The first thing is to create the error and heap objects just as we did when writing the WWS client.

WS_ERROR* error = NULL;
HRESULT hr = WsCreateError( NULL, 0, &error);
if (FAILED(hr))
{
 // ...
}

WS_HEAP* heap = NULL;
hr = WsCreateHeap( 100000, 0, NULL, 0, &heap, error);
if (FAILED(hr))
{
 // ...
}

The next step is to create a service endpoint.

WSHttpBinding_IStringServiceFunctionTable functions = { Reverse };

WS_STRING url = WS_STRING_VALUE(L"http://localhost:8000/StringService");

WS_HTTP_BINDING_TEMPLATE templateValue = {};

WS_SERVICE_ENDPOINT* serviceEndpoint;
hr = WSHttpBinding_IStringService_CreateServiceEndpoint(&templateValue,
    &url, &functions, NULL, NULL, 0,
    heap, &serviceEndpoint, error);
if (FAILED(hr))
{
  // ...
}

Notice how we use the generated WSHttpBinding_IStringServiceFunctionTable to specify the list of functions (just one in our case). Now I use the proxy WSHttpBinding_IStringService_CreateServiceEndpoint to create the end point (and it internally calls WsCreateServiceEndpointFromTemplate). I have used default values for other arguments, but there is a lot of custom configuration that can be done. We’ll now create the service host:

WS_SERVICE_HOST* host;
const WS_SERVICE_ENDPOINT* serviceEndpoints[1];
serviceEndpoints[0]= serviceEndpoint;
hr = WsCreateServiceHost( serviceEndpoints, 1,
    NULL, 0,  &host, error);
if (FAILED(hr))
{
}

We only have one endpoint, but the service host can host multiple endpoints. While I have called WsCreateServiceHost with default arguments (basically passing NULL) it’s possible to set various service properties at this point. The last step is to open the service host.

hr = WsOpenServiceHost(host, NULL, error);

The above code will open the service and start listening on each of the endpoints (just one in our example). For a test console app, use a _getch() so the app won’t exit. Once the app’s done, close and free the service host :

WsCloseServiceHost(host, NULL, error);
WsFreeServiceHost(host);

And also free the heap/error objects :

if (heap)
{
  WsFreeHeap(heap);
}

if (error)
{
  WsFreeError(error);
}

You can now run the service and the WWS client from the last blog entry will connect to it and invoke the reverse function successfully. You can even write a simple WCF client and it’ll connect to this just as if this was a WCF service. I do agree that all these proxies, having to create/free structures, handling HRESULTs etc. may seem a tad foreign if you are coming from a pure C# or VB.NET world. But if you are not put off by C++, and keeping your service or client code native is important to you, then WWS sure seems to be a great way to do it. I do intend to research into WWS a little more in detail, so expect more blog entries and an article or two on the topic in future.

→ 4 CommentsTags: C++ · WWS API

Consuming a WCF service using a native WWS client

July 23rd, 2009 · 4 Comments

I have been meaning to play with Windows Web Services ever since I heard Nikola Dudar talk about it at the MVP Summit earlier this year. It’s natively included with Windows 7, but can also be installed and used from older OSes (XP, Vista, 2003 and 2008). You can write native clients using WWS that can connect to a WCF service, and similarly you can write a WWS native service that can be consumed by a WCF client. It’s so compatible that you can replace either a WCF client or a WCF service with a WWS equivalent without the other party being aware of it.

One of the first things I did was write a very simple WCF service and then connected to it using a simple WWS client. I intend to write a detailed article on that in the next few days but I’ll go through the basic steps in this blog so I can use that as some basic raw material for my article.

The first thing I did was to create a very simple WCF service. Here’s the service interface :

    [ServiceContract]
    interface IStringService
    {
        [OperationContract]
        string Reverse(string s);
    }

    class MyStringService : IStringService
    {
        public string Reverse(string s)
        {
            return new string(s.Reverse().ToArray());
        }
    }

Here’s some slightly stripped out code that shows how the service is created and run.

WSHttpBinding binding = new WSHttpBinding();

// .. set properties on binding

Uri baseAddress = new Uri("http://localhost:8000/StringService");

using (ServiceHost serviceHost = new ServiceHost(
  typeof(MyStringService), baseAddress))
{
    ServiceMetadataBehavior smb =
      serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
    if (smb == null)
        smb = new ServiceMetadataBehavior();

    // .. set properties on smb

    serviceHost.AddServiceEndpoint(
      ServiceMetadataBehavior.MexContractName,
      MetadataExchangeBindings.CreateMexHttpBinding(),
      "mex"
    );

    serviceHost.AddServiceEndpoint(
      typeof(IStringService), binding, baseAddress);
    serviceHost.Open();

Now there are two steps to do before we start writing the WWS native client :

  1. Use svcutil to generate WSDL from the WCF service
  2. Use the Windows WebServices compiler tool (wsutil) to generate proxies (c/h files).

Once you do this, create a native C++ console project, add the c/h files (and remember to disable precompiled headers for the C files). I am not going to show error handling code in the below code, but you need to check the HRESULT for error/success after every call. First thing is to declare some variables and also specify the service URL :

HRESULT hr = ERROR_SUCCESS;
WS_ERROR* error = NULL;
WS_HEAP* heap = NULL;
WS_SERVICE_PROXY* proxy = NULL;

WS_ENDPOINT_ADDRESS address = {};
WS_STRING url= WS_STRING_VALUE(L"http://localhost:8000/StringService");
address.url = url;

WS_STRING is a simple struct that has a WCHAR* (that will point to the string) and a ULONG that will represent the length. I’ve used the WS_STRING_VALUE macro to initialize the string there.

The WWS APIs provide rich error info through the WS_ERROR structure and so we create a WS_ERROR struct using the WsCreateError API call (using default arguments).

hr = WsCreateError(NULL,  0,  &error);
if (FAILED(hr))
{
  //...
}

We also need to create a WS_HEAP object which represents an opaque heap structure (error handling not shown) :

hr = WsCreateHeap(2048, 512, NULL, 0, &heap, error); 

The next step is to create the service proxy :

WS_HTTP_BINDING_TEMPLATE templ = {};
hr = WSHttpBinding_IStringService_CreateServiceProxy(&templ, NULL, 0, &proxy, error);

WSHttpBinding_IStringService_CreateServiceProxy is a proxy function that was generated by wsutil. Internally it calls the WWS API WsCreateServiceProxyFromTemplate but it saves us the hassle of correctly and properly filling up the various arguments. Now, we open the service proxy (connects us to the service endpoint) :

hr = WsOpenServiceProxy(proxy, &address, NULL, error);

At this point we are ready to make calls into the service for which we again use the proxy functions that are generated by wsutil.

WCHAR* result;	

hr = WSHttpBinding_IStringService_Reverse(
        proxy, L"Nishant Sivakumar", &result,
        heap, NULL, 0, NULL, error);

if (FAILED(hr))
{
  // ...
}

wprintf(L"%s\n", result);

WSHttpBinding_IStringService_Reverse is generated for us and is a pretty simple function to use, and it internally wraps the call to the WsCall WWS API function, including correctly wrapping up all the arguments and the return value. Well, that’s pretty much it. Once you are done, just call all the close/free APIs :

if (proxy)
{
  WsCloseServiceProxy(proxy, NULL, NULL);
  WsFreeServiceProxy(proxy);
}

if (heap)
{
  WsFreeHeap(heap);
}

if (error)
{
  WsFreeError(error);
}

I was absolutely thrilled when I ran the console app and it successfully connected to the WCF service. The native client is about twice as long (number of lines of code) as an equivalent managed WCF client would have been but that’s a small price to pay for the ability to consume a WCF service in pure native code. In a later blog entry I will write about how the WCF service itself can be replaced with an identical WWS service (both WCF and WWS clients will continue to work the same).

→ 4 CommentsTags: C#/.NET · C++ · Indigo · WWS API

.NET 4.0 : Arrays are now structurally equatable

July 20th, 2009 · No Comments

In .NET 4.0, arrays implement IStructuralEquatable which lets you equate two arrays based on their contents.

int[] array1 = new int[] { 3, 5, 9 };
int[] array2 = new int[] { 3, 5, 9 };

IStructuralEquatable equatableArray1 = array1;
Console.WriteLine(
    equatableArray1.Equals(
        array2, EqualityComparer<int>.Default));

The above code outputs True. You can use it with your custom types too :

class Person : IEquatable<Person>
{
    public string Name { get; set; }

    public int Age { get; set; }

    public bool Equals(Person other)
    {
        return this.Name == other.Name && this.Age == other.Age;
    }
}

var person1 = new[]
{
    new Person() { Name = "John", Age = 17 },
    new Person() { Name = "Alice", Age = 18 }
};

var person2 = new[] {
    new Person() { Name = "John", Age = 17 },
    new Person() { Name = "Alice", Age = 18 }
};

IStructuralEquatable equatablePersonArray1 = person1;
Console.WriteLine(
    equatablePersonArray1.Equals(
        person2, EqualityComparer<Person>.Default));

→ No CommentsTags: C#/.NET · CLR/.NET BCL

Setting VC++ directories in VS 2010

July 17th, 2009 · 1 Comment

In VS 2010, Tools/Options does not have a VC++ directories tab (where you normally set the include/lib search folders). Instead if you take project settings for a C++ project, you’ll see VC++ Directories listed under Configuration Properties. Of course these are per project and not per user (as in VS 2008). If you want to change it for the current user globally, bring up the Property Manager and then you’ll see various property sheets under Debug and Release (there may be more configurations on your machine). Just edit the property sheet named Microsoft.Cpp.Win32.user and now you’ll have set it globally for your user for that specific configuration.

→ 1 CommentTags: C++ · VC++ 2010

Article : Delayed Delegate Invoker

July 15th, 2009 · 1 Comment

Here’s my latest article that discusses a simple utility class that lets you queue up delegates and then execute them at a later time in a first-in first-out order. I wrote this when I had a situation where I was doing some rather complex processing based on property changed event notifications, and I found that some of the earlier notifications were going unhandled because the processing code had not completed a stable initialization at that point. So I queued up my various event handlers and then invoked them once I was sure it was safe to do so. Other uses I can think of include using this class as a macro recorder – just queue up all your mouse and keyboard actions, and invoke them during playback.

→ 1 CommentTags: C#/.NET

A boolean lock using IDisposable

June 23rd, 2009 · 7 Comments

While there are more complex and functional lock mechanisms, I wanted a very simple lock that would tell me if an operation was locked or not. Normally I would just have a flag that’d be true or false, but I found that it was not always easy to remember to set the flag on or off, and also to make sure the flag was set at the right place. So I came up with this class :

public class BooleanLock
{
    public bool Locked { get; private set; }

    public class BlockLock : IDisposable
    {
        private BooleanLock _parent;

        public BlockLock(BooleanLock parent)
        {
            _parent = parent;
            _parent.Locked = true;
        }

        #region IDisposable Members

        public void Dispose()
        {
            _parent.Locked = false;
        }

        #endregion
    }

    public BlockLock Lock()
    {
        return new BlockLock(this);
    }
}

Now I could use it this way :

// Declare a field as a lock
private BooleanLock _myUpdateLock = new BooleanLock();

// Check for lock
private void UpdateSomeProperty(bool reset)
{
    if (_myUpdateLock.Locked)
        return;

    // . . .

And here’s where the lock is set :

// Part of the function is not re-entrant, so we use a lock there
private void OnSomePropertyChanged()
{
    if (some-condition)
    {
        using (_myUpdateLock.Lock())
        {
            // do non-re-entrant stuff
        } <-- lock is released here automatically

The big advantage here is that the C# compiler’s using-block behavior handles complex try-catch scenarios that I would otherwise have had to implement on my own.

→ 7 CommentsTags: C#/.NET

Checking for Design-Mode

June 21st, 2009 · 1 Comment

The DesignMode property does not always return the correct value, specially for nested controls or for child controls instantiated in their parent control’s constructors. One workaround is to check for LicenseManager.UsageMode and see if it’s equal to LicenseUsageMode.Runtime, but even that won’t work all the time. It will always return Runtime from event handlers and worker threads, so a more guaranteed approach is to see if the current process-name is devenv. Of course that’s a slightly heavier call so we should still check for LicenseManager.UsageMode first, and only check the process-name if we have to.

bool isDesignMode = LicenseManager.UsageMode == LicenseUsageMode.Designtime
  || Process.GetCurrentProcess().ProcessName.ToLowerInvariant().Contains("devenv");

→ 1 CommentTags: C#/.NET · Windows Forms

Exposing List<T> vs IList<T>

June 14th, 2009 · 3 Comments

Unless you specifically want to expose a List<T> via a public interface (either as a return type or as a method argument), it’s a better idea to expose an IList<T>, ICollection<T>, or even an IEnumerable<T> depending on your needs. Recently I had to implement a generic list class that implemented property notifications and for this purpose I wrote a collection class that implemented IList<T> which by the way implements both ICollection<T> and IEnumerable<T>. I thought it’d be a simple matter to change members of certain types that used a List<T> to use this new collection class.

Unfortunately, I found that there were several methods in containing classes as well as calling classes that expected List<T> objects (even though the callers only used IList<T> or ICollection<T> members). Eventually I ended up having to change calling code and utility helper methods to use an IList<T> or ICollection<T> as appropriate. (Note that exposing the notification list was out of the question as it was not accessible to some of the callers and it is not good practice anyway).

In some cases the code used List<T> specific methods like Find, but if you have LINQ available then you don’t need to use the List<T> methods since you have alternate and usually more useful extension methods that you can use. I suppose I am over-specializing here by talking about List<T> in particular because it’s probably a good general practice to always expose the least derived class that you really need to.

Note that if you really need to expose a solid class without letting the users change the collection, then using ReadOnlyCollection<T> would be the correct approach compared to directly exposing the List<T> or Collection<T> object or their related interfaces like IList<T>.

→ 3 CommentsTags: C#/.NET

C# 4.0 and variant generic delegates

May 29th, 2009 · 1 Comment

Continuing on from my previous blog entry, in this entry I will talk about variant generic delegates. Just as with generic interfaces, generic delegates can use out and in to specify covariant and contravariant parameters respectively. And the MSIL equivalents are the + and - symbols.

Here are three variant generic delegate declarations:

delegate T CovariantDelegate<out T>();
delegate void ContraVariantDelegate<in T>(T t);
delegate T1 ContraAndCovariantDelegate<out T1, in T2>(T2 t2);

The rules are the same as with generic interfaces. The covariant delegate can only use the generic parameter as a return type, while the contravariant delegate can only use it as a delegate argument and not as a return type. The third delegate is both covariant and contravariant but with respect to two separate parameters. And here’s how these delegates can be used:

static Derived SomeFunc()
{
    return new Derived();
}

static void SomeOtherFunc(Base b)
{
}

static Derived AnotherFunc(Base b)
{
    return new Derived();
}

private void DoDelegates()
{
    CovariantDelegate<Base> covariantDeleg = SomeFunc; <--(#1)

    ContraVariantDelegate<Derived> contraDeleg = SomeOtherFunc; <--(#2)

    ContraAndCovariantDelegate<Base, Derived> contraCovarDeleg = AnotherFunc; <--(#3)
}

(#1) : Covariance at play here. Even though SomeFunc returns a Derived type, we use it to instantiate a delegate that expects a Base type.

(#2) : Contravariance here. The delegate expects a Derived argument, but we pass it a method that takes a Base argument.

(#3) : This is essentially a mix of (#1) and (#2).

Here’s a more realistic use of variance in generic delegates:

class Item
{
    . . .

    public int Code { get; set; }
}

class Book : Item
{
    public string Title { get; set; }
}

class DVD : Item
{
    public string Description { get; set; }

    public int Duration { get; set; }
}

Item FindItem(string searchText, Func<string, Item> findFunc)
{
    return findFunc(searchText);
}

Notice how the FindItem method’s second parameter is a Func<> object that itself takes a string and returns an Item. Func’s return type parameter is covariant, and that’s what we can take advantage of. The code below shows two methods, one that searches for a book, and the other that searches for a DVD.

static List<Book> books = < . . . >

static Book FindBook(string searchText)
{
    return books.FirstOrDefault(book => book.Title == searchText);
}

static List<DVD> dvds = < . . . >

static DVD FindDVD(string searchText)
{
    return dvds.FirstOrDefault(dvd =>
        dvd.Description.StartsWith(searchText)
        || searchText.Contains(dvd.Duration.ToString()));
}

The following code shows how to call FindItem using a delegate of our choice.

Item book = FindItem("C++/CLI in Action", FindBook);

Item dvd = FindItem("Batman", FindDVD);

In the first call, we pass a method that returns a Book, whereas the method signature expects a method that returns an Item. But since Func<>’s return parameter is covariant, this works fine. Essentially we are passing a Func<string, Book> as a Func<string, Item> argument. It’s the same for the second call too except that we have a DVD instead of a Book.

Now let’s see a contravariant delegate example. Consider the following method:

void ShowItemCode<T>(T item, Action<T> showFunc)
{
    showFunc(item);
}

It takes an Action<T> as the second argument which is a contravariant generic delegate. Now consider the following code:

static void ShowCode(Item item)
{
    Console.WriteLine(item.Code);
}

. . .

Book book = < initialize here . . .>
ShowItemCode(book, ShowCode);

DVD dvd = < initialize here . . .>
ShowItemCode(dvd, ShowCode);

In the first case we are calling ShowItemCode<Book> which expects Action<Book> as the second argument. But we pass ShowCode(Item) which matches Action<Item> yet it works because Action<> is contravariant.

Remember how in the previous entry I had mentioned a case where a covariant parameter type can be used as the parameter type for a contravariant delegate argument? Well, here’s an example of that:

interface ITestCovariant<out T>
{
    //void Bar(T t); <-- won't compile
    void Foo1(Action<T> func);
    void Foo2(Func<T, bool> func);
}

Even though T is a covariant parameter, we can use it as the parameter type for Action<> since Action is contravariant. I have also used it as the first type argument for the Func<> argument because though Func<> has a covariant return type, it’s input argument generic types are contravariant. Similarly for a contravariant interface:

interface ITestContravariant<in T>
{
    //T Bar(); <-- won't compile
    Func<T, bool> Foo1();
    Action<T> Foo2();
}

Here, we have a contravariant parameter T, but we’ve indirectly used it in the return type by using it to set the contravariant parameters in the Func<> and Action<> delegates.

→ 1 CommentTags: C#/.NET

C# 4.0 and variant generic interfaces

May 27th, 2009 · 1 Comment

The CLI supports variant generic parameters for interfaces as well as delegates, and C# 4.0 has added support for that. In this blog entry I’ll talk a little about variance in generic interfaces, and in a later entry I will talk about variance in delegates.

Covariance allows you to use a more derived type than what’s specified by the generic parameter, whereas contravariance allows you to use a less derived type. Generic interfaces can be covariant, contravariant, or both (though not for the same parameter).

Consider the following code:

class Base
{
}

class Derived : Base
{
}

interface ICovariant<out T> <-- covariant parameter
{
}

class Covariant<T> : ICovariant<T>
{
}

interface IContraVariant<in T> <-- contravariant parameter
{
}

class ContraVariant<T> : IContraVariant<T>
{
}

There’s a base class and a derived class, a covariant interface, an implementation of that interface, a contravariant interface, and its implementation. In C# a covariant parameter is prefixed with out, and a contravariant parameter is prefixed with in. In MSIL the symbols + and - are used for covariance and contravariance. (Note : at the time of writing, Reflector does not recognize or show variant generic parameters, but ildasm does show it correctly).

Here’s some code that shows the variance in action:

ICovariant<Base> baseCov = new Covariant<Base>();
ICovariant<Derived> derivedCov = new Covariant<Derived>();
baseCov = derivedCov; <-- covariance

IContraVariant<Base> baseContra = new ContraVariant<Base>();
IContraVariant<Derived> derivedContra = new ContraVariant<Derived>();
derivedContra = baseContra; <--contravariance

In the first case, we were able to assign a more derived generic instantiation to be assigned to a less derived one. In the second case we did the exact opposite. The Base Class Library has been updated to support covariance and contravariance in various commonly used interfaces. For example, IEnumerable<T> is now a covariant interface – IEnumerable<out T>. This lets us do:

IEnumerable<object> objects = new List<string>();
IEnumerable<Base> baseList = new List<Derived>();

That was something you could not do prior to C# 4.0. Now you won’t have to use LINQ’s Cast<>() as often as you may doing now. There are some rules to follow when using variant generic parameters.

For covariant generic parameters, the generic parameter can only be a return type, it cannot be used as a method argument. It also cannot be used as a generic constraint. (Note : A contravariant delegate can be used as a method parameter that uses the generic parameter as its generic parameter type. I’ll talk about it in my entry on variant delegates)

For contravariant generic parameters, the rules are basically reversed. The parameter type can only be a method argument or a generic type constraint, it cannot be used as a return type. Here’s an interface that has both contravariant and covariant generic parameters.

interface IContraAndCovariant<in T1, out T2>
{
    //T1 Foo(T2 value); <-- won't compile

    T2 Foo(T1 value);
}

Here’s a more realistic example of where covariance comes in very handy:

class Item
{
    public void CheckOut()
    {
        Console.WriteLine("{0} checked out", Code);
    }

    public int Code { get; set; }
}

class Book : Item
{
    public string Title { get; set; }
}

static void CheckOutItem(IEnumerable<Item> source, int code)
{
    try
    {
        source.First(item => item.Code == code).CheckOut();
    }
    catch (InvalidOperationException ex)
    {
        Debug.WriteLine(ex.Message); // invalid code
    }
}

CheckOutItem expects an IEnumerable of Item elements, but because IEnumerable<T> is covariant, I can do this:

List<Book> books = new List<Book>()
{
    new Book(){Code = 99, Title = "C++/CLI in Action"},
    new Book(){Code = 101, Title = "Ajax in Action"},
    new Book(){Code = 105, Title = "ASP.NET Ajax in Action"},
};

CheckOutItem(books, 99);

I have passed an IEnumerable<Book> to a method where an IEnumerable<Item> was expected. And here’s a realistic example of where contravariance can be used:

class ItemComparer : IComparer<Item>
{
    public int Compare(Item x, Item y)
    {
        return x.Code.CompareTo(y.Code);
    }
}

private void ContravarianceTest()
{
    List<Book> books = new List<Book>()
    {
        new Book(){Code = 199, Title = "C++/CLI in Action"},
        new Book(){Code = 501, Title = "Ajax in Action"},
        new Book(){Code = 105, Title = "ASP.NET Ajax in Action"},
    };

    books.Sort(new ItemComparer());
}

I used the List<T>.Sort overload that takes an IComparer<T> argument which in this case would have been an IComparer<Book> but since IComparer<T> is contravariant with regard to T, I could pass my ItemComparer class which is actually an IComparer<Item>.

Funnily, now that it’s available it’s kind of hard to think of how people managed to go without this all these years. It’s more the sort of feature that gets a “woah, we didn’t have this before!” response from people. In a later entry I will discuss variance in delegates.

→ 1 CommentTags: C#/.NET

Named and optional parameters in C# 4.0

May 25th, 2009 · 3 Comments

One commonly heard grievance about C# was how it did not support optional parameters. Well C# 4.0 not only has that, but you can also specify parameters by name.

Consider the following two examples :

public void RepeatText(string text, int count = 3)
{
    while (count-- > 0)
    {
        Console.WriteLine(text);
    }

    Console.WriteLine();
}

public void RepeatDecoratedText(string text, string decoration = "Mr.", int count = 3)
{
    while (count-- > 0)
    {
        Console.WriteLine("{0} {1}", decoration, text);
    }

    Console.WriteLine();
}

RepeatText has an optional parameter count with a default value of 3, while RepeatDecoratedText has two optional parameters. The MSIL generated for these methods are as follows (simplified, and not exact) :

.method public void RepeatText(string text, [opt] int32 count)
{
    .param [2] = int32(3)

.method public void RepeatDecoratedText(string text, [opt] string decoration, [opt] int32 count)
{
    .param [2] = string('Mr.')
    .param [3] = int32(3)

[opt] is a parameter attribute that indicates that this parameter is optional and that the default value will be specified by .param entries. These methods can now be called as follows:

RepeatText("Nish");
RepeatText("Ant", 2); 

The compiler generates code with the optional values filled in as needed:

RepeatText("Nish", 3); <-- 2nd param set via .param value
RepeatText("Ant", 2); <-- No extra work needed

You can also now pass an argument by name. This is particularly useful when you want to skip some optional args, but provide others.

RepeatDecoratedText("Nish", count: 2);
RepeatDecoratedText(count: 2, text: "Ant");
RepeatDecoratedText(decoration: "The super", count: 2, text: "Ant");

That gets compiled as:

RepeatDecoratedText("Nish", "Mr." 2);
RepeatDecoratedText("Ant", "Mr.", 2);
RepeatDecoratedText("Ant", "The Super", 2);

So basically, the parameters are either filled in via the named values provided or via the default optional values. Note that you can write optional value methods using attributes too. Example:

public void RepeatTextDuplicate(string text, [Optional, DefaultParameterValue(3)] int count)
{
    RepeatText(text, count);
}

// . . .

RepeatTextDuplicate("Nish");
RepeatTextDuplicate("Nishant", 5);

The MSIL generated for this method is identical to what you’d have got with the direct C# syntax (used earlier).

As with dynamic types, apparently the biggest beneficiaries of these new named and optional parameter features are developers who interop with Office. Just like in VBScript you can now avoid having to provide optional arguments, and can also provide a named argument directly. For others, optional parameters will definitely help reduce the number of method overloads you need to write, and where there are methods that have more than a few optional parameters, the ability to call them by specifying named parameters will result in cleaner and more legible code.

→ 3 CommentsTags: C#/.NET

A quick look at the C# 4.0 dynamic type

May 22nd, 2009 · 1 Comment

VS 2010 Beta 1 includes some C# 4.0 features and though I have been reading about some of the new stuff on various blogs and forums, I only got to play with it very recently. Put simply, the dynamic keyword allows you to declare and use types that are not type-checked during compilation. They are resolved at runtime using the DLR.

Here’s a simple class that has a dynamic field, a method that has a dynamic argument, and a dynamic property:

class Dynamic
{
    private dynamic data;

    public void SetData(dynamic data)
    {
        this.data = data;
    }

    public dynamic MetaData { get; set; }

    public void Display()
    {
        Console.WriteLine("{0} {1}, {2} {3}",
            data, data.GetType(), MetaData, MetaData.GetType());
    }
}

Using the class is quite straightforward:

private void Foo()
{
    var d = new Dynamic();
    d.MetaData = 100; <-- Int32
    d.SetData(99); <-- Int32
    d.Display();
    d.MetaData = 100f; <-- Single
    d.SetData("hello"); <-- String
    d.Display();
}

Notice how I keep using different types at runtime for calling the same methods and properties. If you look at the IL via Reflector, you’ll see that dynamic types are internally treated as System.Object. Intellisense within VS 2010 will also give you System.Object members since that’s what they are guaranteed to have.

There are three dynamic calls in the Display method. A nested static class is generated inside the Dynamic class, and it will have one static CallSite<> field per dynamic call. In this case, there are three such fields. Whenever the dynamic calls are made, it’s these DLR call sites that come into play. An extremely simplified explanation of what happens is that the DLR internally uses reflection to figure out what type the dynamic object is at runtime. There is also caching done so that type-matching (or mapping) is not repeated unnecessarily. Of course the implementation is quite complex and you could probably spend weeks going through the code in Reflector. Note that if you make dynamic calls in a different method, there will be another static class generated – so it seems to be one inner class per method.

Consider the following simple method:

public void Test()
{
    var type = data.GetType();
}

A class will be generated similar to the following (I’ve made this easy to read – so this is not an accurate representation of the generated code):

[CompilerGenerated]
private static class SiteContainerForTest
{
    public static CallSite<FUNC<CALLSITE, object, object>> callSiteGetType;
}

And the method Test gets compiled into:

public void Test()
{
    if (SiteContainerForTest.callSiteGetType == null)
    {
        SiteContainerForTest.callSiteGetType = CallSite<Func<CallSite, object, object>>.Create(
            new CSharpInvokeMemberBinder(
                CSharpCallFlags.None,
                "GetType", <-- the name of the dynamic member
                typeof(Dynamic),
                null,
                new CSharpArgumentInfo[] { new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null) }
            )
        );
    }

    object type = SiteContainerForTest.callSiteGetType.Target(
      SiteContainerForTest.callSiteGetType,
      this.data <-- the dynamic object
    );
}

The call site’s Target will be of type Func<CallSite, object, object>, and the return type is object (because at compile time that’s what the local variable type was defined as, since we don’t know what type it would be at that time). It’s at this point that dynamic binding is done. Fortunately for us, it’s all done behind the scenes and we are protected from having to write all this code ourselves. Assuming data is an Int32 at this time, Int32’s GetType is called (and since it doesn’t have one, Object’s GetType is invoked).

You can also use dynamic types locally (a site container class is generated for the containing method) :

dynamic d = 1;
string s = d.ToString();
Console.WriteLine(s);

d = "dynamic data";
Console.WriteLine(d.Length);

d = 33;

try
{
    int len = d.Length; <-- Invalid dynamic call on an Int32 object
}
catch (RuntimeBinderException ex)
{
    Console.WriteLine(ex.Message);
}

When I try to use the non-existent Length property on an Int32 value, the runtime will throw a RuntimeBinderException. And it even gives a very useful error message : ‘int’ does not contain a definition for ‘Length’.

Overall, one of the most celebrated uses of dynamic types is supposed to be for Office interop. You no longer have to do endless casts and mid-level variables for debugging. It’s just as easy as using classic VBScript. At this point, unless you want to interop with Word or Excel, I can’t think of too many scenarios where this will come in handy. Maybe someone who’s more functionally oriented than I am can think of some common scenarios.

→ 1 CommentTags: C#/.NET · General

Tip : Flush the keyboard buffer from C#

May 19th, 2009 · No Comments

Here’s another tip from an MSDN forum discussion. Someone wanted to know how to flush the keyboard buffer in a C# console application.

Here’s a simple hack to do this :

private static void FlushKeyboard()
{
    while (Console.In.Peek() != -1)
        Console.In.Read();
}

Now you can use it as follows :

char x = (char)Console.Read();
FlushKeyboard();
char y = (char)Console.Read();
Console.WriteLine("{0}, {1}", x, y);

Even if you enter more than a single character after the first call to Read(), the second Read() will not be affected.

→ No CommentsTags: C#/.NET · General

Tip – Sending multi-line email using the mailto: protocol

May 15th, 2009 · No Comments

A few weeks ago someone asked on the MSDN forums how he could use the mailto: protocol to send a multi-line email. The trick is to use %0D%0A in lieu of \r\n.

Here’s a small C# code snippet that shows how to do this :

string command = "mailto:abc@abc.com?subject=The Subject&body=Ln 1%0D%0ALn 2";
Process.Start(command);

→ No CommentsTags: C#/.NET

Article : A generic Trictionary class

March 11th, 2009 · 4 Comments

I just published an article on a generic Trictionary class :

The article describes a Trictionary class that is essentially a dictionary except that for each key there are two values, both of differing types. In many cases instead of doing this, the proper approach would most likely to use a struct that would have those two types as members. But there may also be scenarios where you may want to avoid having to unnecessarily create a struct just for this purpose. You could also use an anonymous type, but that’s really not so different in the sense you still end up having a new type in your assembly. Read the article for more info.

Note that the article was inspired by another Trictionary article on Code Project submitted by Joe Enos.

→ 4 CommentsTags: C#/.NET · CLR/.NET BCL

System.String and intellisense for Linq extension methods

March 7th, 2009 · 1 Comment

Someone was recently complaining in the MSDN forums that intellisense did not work for strings when it came to the Linq extension methods. If you are wondering what that’s about, System.String is an IEnumerable<char> so you can do all of the Where, Select operations on any string object. Here’s a contrived example :

string s = "What's cooking in Alabama?";
char[] vowels = new[] {'a', 'e', 'i', 'o', 'u'};
char[] nonVowels = s.Where(c => !vowels.Contains(
    Char.ToLower(c))).ToArray();
Console.WriteLine(new string(nonVowels));

You just need to manually type in the method name (like Where) and once you do that you’ll then start getting intellisense. You just won’t get it for the starting string object. If you really want it there too, you can use an extra IEnumerable<char> variable and then use that instead of the string. Now you will get full intellisense.

IEnumerable<char> chars = s;

The String class is already equipped with a lot of useful methods, and there’s always the Regex class if you really need some complex string manipulation. So I am not sure there are too many scenarios where you’d actually want to use Linq with a string, but to each his own :-)

→ 1 CommentTags: C#/.NET

An interesting week in Seattle

March 6th, 2009 · 5 Comments

Last week I attended the 2009 MVP Summit held at Redmond/Seattle and I’ve got to say that I had two rather peculiar experiences whilst there. The first incident was on the way to Seattle – it snowed in Atlanta of all things to happen and this resulted in dozens of cancelled and delayed flights. My flight was scheduled for a 2:30 PM departure and after a 3 1/2 hour delay where they pushed back the boarding time every 30 minutes, we finally boarded at 6 PM. Once we got in the aircraft we waited on the tarmac for another 3 1/2 hours more before take-off as we had to wait in line behind dozens of other flights for de-icing. I am still not sure why they couldn’t have us wait outside (at the gate) and let us board after the de-icing. The air was pretty stuffy inside because the air-conditioners seemed to be at half power. And after take-off they ran out of food when it was my turn to order – so yeah, that didn’t help either. It was one of the nastiest experiences I’ve had in an airport/flight in my entire life – one that I hope will not be repeated in future.

The second incident occurred on Tuesday night (or rather Wednesday morning). I was at the Grand Hyatt (17th floor) and had gone to bed close to 1 AM as I had gone for a late dinner/chat with an old friend. Around 4:30 AM or so this really loud siren came on and an even louder announcement was repeated instructing all occupants to move to the nearest staircase and to descend to the first floor immediately. It was also announced that the elevators were shut down. I wasn’t sure if it was a fire-emergency or some temporary air-pollution – in any case, I put on my shoes, picked up my laptop and climbed down the 17 set of stairs (16 maybe if they didn’t have a 13th floor, didn’t feel like counting then). I found a few dozen equally incredulous folks downstairs wondering what the heck had just happened. We watched the fire-trucks come and the firemen go up – and all this time we were all out on the streets. A few minutes later, they said everything was alright and said we could go back up to our rooms. There was a further wait of 20 minutes or so as we waited for an engineer to come down and reset the elevator system – and I didn’t want to climb up the 17 floors, not with my laptop. The worst part of the incident was when we found out that some dim-witted inconsiderate jerk had been smoking in a non-smoking floor which was what set off the fire-alarm. So they had to evacuate that floor as well as the floors directly above and beneath it.

The nice thing about the trip was that the summit was pretty good, we had some interesting technical sessions, the food was great, and it was good to catch up with some fellow MVPs and Microsoft buddies – some of whom I’ve only met at Microsoft summits and never outside Redmond.

→ 5 CommentsTags: General