C#: Use System.Diagnostics.Trace and DbgView within a WPF-Application


One of my favorite tools to debug MFC-Applications was the Win32-call:

::OutputDebugString( "Test\n" );

You can use it to trace information withing your application during runtime without a log-file. You only have to run the tool DbgView to monitor these log-entries ( if you want to try it out you can download DbgView here. )

Because I am currently working with C# in my job I wanted to use this tool as well for WVF-applications. And of course there is a corresponding API-method in the .NET-framework called:

Trace.WriteLine( string msg );

You can find the documentation here.

It is easy to use. Just insert your Trace-log-entries in your code. When you want to take a look into your application you can start DbgView to see, what is ongoing. Just make sure, that you have defined

#define TRACE

at the beginning of your source-file. Here is a small example:

#define TRACE

using System.Diagnosics;

class Test {
    static int main() {
        Trace.WriteLine("Hello, world!" );
        Exit(0);
    }
}

C#: Calling a generic from a generic with surprises


I am currently working on C# wit generics. The base concept seems to be the same as in C++ ( which I really like honestly spoken ).
And I tried to use specialization. There was a class which needs to deal with special data types. And for some special cases you need a type-specific semantic, because bool cannot be added for example. So I tried to do something like this:

public class MyGeneric<T> {
  T mValue;
  public MyGeneric<T>() {}
  public OnMethod( T v ) {
    mValue = v;
  }
  public OnMethod(bool v ) {
    mValue = !v;
  }

  static main() {
    MyGeneric<int> i = new MyGeneric<int> i();
    i.OnMethod(1); // Will call the generic method
    MyGeneric<bool> b = new MyGeneric<bool> i();
    b.OnMethod(true); // Will call the specialized method for bool
  }
}

Looks greate, I thought. problem soled I thought. Let’s integrate it into your application and continue to live a happy life again I thought. I was so wrong …

Because when calling a generic method from a generic method this specialization will not work:


public class MyCaller<T> {
  MyGeneric<T> mClassToCall;
  ...
  public void MethodCaller<T>( T v ) {
    mClassToCall.OnMethod( v );
  }
}
public class MyGeneric<T> {
  T mValue;
  public MyGeneric<T>() {}
  public OnMethod( T v ) {
    mValue = v;
  }
  public OnMethod(bool v ) {
    mValue = !v;
  }

  static main() {
    MyCaller<bool> boolCaller = new MyCaller<Bool> i();
    boolCaller.MethodCaller(true); // Will call the generic method public OnMethod( T v )
  }
}

This will not call the specialization. You need to add special traits to deal with this situation.

To be continued …