[Mono-dev] gmcs and The Future
Marek Safar
marek.safar at seznam.cz
Thu Feb 5 13:54:35 EST 2009
Hi,
> On Thu, 2009-02-05 at 12:10 -0500, Avery Pennarun wrote:
>
>> (The reason I use cpp, incidentally, is so I can implement C-style
>> assert() and check() macros that actually print the condition being
>> tested as part of the assertion message. There seems to be no other
>> way to do this in C#, which is too bad.)
>>
>
> There is now. It's not the most performant technique around, but your
> Assert() or Check() methods could take an Expression<T>. The
> Expression<T> can then be converted into a string for diagnostic
> messages, and converted into a delegate for the actual condition check,
> e.g.:
>
> [Conditional("DEBUG")]
> static void Assert<T>(T value, Expression<Func<T, bool>> e)
> {
> Func<T,bool> d = e.Compile();
> if (!d (value)) {
> // Convert `e' to a string and log
> }
> }
>
> // ...
>
> Assert(self, v => v != null);
>
Here is slightly simplified version
[Conditional("DEBUG")]
static void Assert (Expression<Func<bool>> e)
{
var d = e.Compile ();
if (!d ()) {
Console.WriteLine (((LambdaExpression)e).Body.ToString ());
}
}
public static void Main ()
{
object self = null;
Assert (() => self != null);
}
Marek
More information about the Mono-devel-list
mailing list