Creating an extension method in a .Net 2.0 project, compiling with C # 4.0

I have an old product that I need to upgrade written in C # and .Net 2.0. The project has been updated to work with Visual Studio 2010 (which includes the C # 4.0 compiler), but I cannot update the frame from 2.0 to any higher version.

I found several articles (like this question ) that were written during VS 2008, which comes with the C # 3.0 compiler, stating that you can create your own extension methods by specifying your own extension method attribute class for projects that were written using the 2.0 framework. However, I cannot find the link if necessary using C # 4.0 in a .Net 2.0 project.

In my project, will I still need to define my own extension attribute class or improve the C # 4.0 compiler to make the process easier?

+4
source share
1 answer

It seems I can not find the link if necessary using C # 4.0 in a .Net 2.0 project.

Yes it is. The compiler needs this attribute. Regardless of whether you define it yourself or use the one located in System.Core , it is up to you. Although in your specific case, System.Core not an option, since it is only part of .NET 3.5.

After upgrading to a later version 3.5 or later, you can completely remove this attribute from your project and simply use it in System.Core .

If you updated Visual Studio 2010; then you are using the c # 4.0 compiler. That means all you need is an ExtensionAttribute :

 namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class ExtensionAttribute : Attribute { } } 

It must be in this exact namespace.

Once you get this place, you can declare the extension method in the usual way (since you are using the C # 4.0 compiler):

 public static class Extensions { public static string ToTitleCase(this string str) { //omitted } } 

And then use it as an extension method:

 var str = "hello world"; str.ToTitleCase(); 

You yourself should never really put ExtensionAttribute on anything; The C # 4.0 compiler does this for you. Essentially, all compiler needs should be able to find an attribute named ExtensionAttribute .

+3
source

Source: https://habr.com/ru/post/1392717/


All Articles