Wednesday, June 13, 2012

Calling C# 4/3/2.... Using the new C# 5 Caller Information with C# 2,3,4...

Thomas Levesque's .NET blog - Using C# 5 caller info attributes when targeting earlier versions of the .NET framework

Caller info attributes are one of the new features of C# 5. They’re attributes applied to optional method parameters that enable you to pass caller information implicitly to a method. I’m not sure that description is very clear, so an example will help you understand:

image

The method above takes several parameters intended to pass information about the caller: calling member name, source file path and line number. The Caller* attributes make the compiler pass the appropriate values automatically, so you don’t have to specify the values for these parameters:

image

This is of course especially useful for logging methods…

...

Notice that the Caller* attributes are defined in the .NET Framework 4.5. Now, suppose we use Visual Studio 2012 to target an earlier framework version (e.g. 4.0): the caller info attributes don’t exist in 4.0, so we can’t use them… But wait! What if we could trick the compiler into thinking the attributes exist? Let’s define our own attributes, taking care to put them in the namespace where the compiler expects them:

image

If we compile and run the program, we can see that our custom attributes are taken into account by the compiler. So they don’t have to be defined in mscorlib.dll like the “real” ones, they just have to be in the right namespace, and the compiler accepts them. This enables us to use this cool feature when targeting .NET 4.0, 3.5 or even 2.0!

..."

As I've said today, I love a good hack... :)

 

Related Past Post XRef:
"...known as the Matrix..." The C# Evolution Matrix that is...

1 comment:

Unknown said...

Reminds one of how you could get extension methods in 2.0.