Is the CallerMemberName attribute in 4.5 "able to be faked"?
Asked Answered
C

1

26

So .NET 4.5 introduces the CallerMemberNameAttribute, which seems like a godsend to anyone working with WPF and implementing INotifyPropertyChanged - my question is this: Is the attribute intrinsically tied/supported by the 4.5 5.0 compiler, or is it more of a syntactical sugar helper by the environment, much like one could fake out Visual Studio by declaring an ExtensionAttribute of your own, magically turning on LINQ syntax?

Edit: (sorry Jon!) I guess I'm asking if one can "enable" the functionality of the CallerMemberNameAttribute in .NET 4.0 via redeclaration of the attribute in the proper namespace, much like one can "enable" LINQ query syntax in .NET 2.0 by proper declaration of the ExtensionAttribute class. My strong suspicion is no, naturally...

Put yet another way: I want to know if I can benefit from the functionality of CallerMemberName without upgrading to .NET 4.5/5

Hopefully that's more clear...

NinjaEdit #2: Sigh...version numbering conventions are confusing!

Criminal answered 14/11, 2012 at 15:33 Comment(2)
Your question is very unclear - there's no 4.5 compiler, because there's no C# 4.5. Are you asking whether you could use the C# 5 compiler against an earlier version of the framework, creating your own attributes that look the same as the ones in .NET 4.5? (Like the ExtensionAttribute is just tied into the C# 3+ compiler, and does not depend on the "environment".)Casillas
@JerKimball: there is no .NET 5, there is .NET 4.5 and C# 5.Icken
I
51

Yes, you can, exactly as you could use LINQ and .NET 2, as you said. I use the following in a .NET 4.0 project with the VS2012 compiler with success:

namespace System.Runtime.CompilerServices {

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
    public sealed class CallerMemberNameAttribute : Attribute {
    }

}

Be very careful that everyone on the project is using VS2012, otherwise they'll get silent bugs because CallerMemberNameAttribute didn't do anything and null was passed as the parameter default.

Edit 2013-06-28: Consider installing the Microsoft.Bcl NuGet package that provides CallerMemberNameAttribute (and some other classes from .NET 4.5) for .NET 4 and Silverlight rather than doing it manually.

Icken answered 14/11, 2012 at 15:51 Comment(3)
Thanks! I was unsure if it was another "environment-enabled" attribute or something deeper - not having the assemblies installed (and not in a position presently to install them), my normal method of reflectoring was unavailable. :)Criminal
Installing Microsft.Bcl introduces dependency on kb2468871, so I'd avoid that if possibleChouinard
@Chouinard Why? It is a patch for .NET from 2011. Everyone should have installed it already for security and stability issues.Craniometry

© 2022 - 2024 — McMap. All rights reserved.