Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare an extension with global scope across the solution

I'm trying to write an extension (actually taken from Case insensitive 'Contains(string)')

It compensates for the Turkey Test when doing string comparison. The extension itself is simple:

public static bool Contains(this string source, string toCheck, StringComparison comp)
{
  return source.IndexOf(toCheck, comp) >= 0;
}

Now the key is I'm trying to figure out where/how to include this so that across the entire solution (which contains multiple projects and each project has it's own namespace and classes), it can be readily accessed by string.Contains without having to do class.string.Contains or some other way.

Say there is a project 'Util' which is included in all other projects, is there someway I can put this in Util (without a class?) so that it can be globally referenced across the solution as string.Contains?

Is this even possible? If so how?

like image 425
rboy Avatar asked Feb 14 '23 00:02

rboy


1 Answers

Although I don't recommend it, you can easily achieve what you are up to by including your code in public static classes under the namespace System.

namespace System
{
   public static class CaseInsensitiveContains
   {
       public static bool Contains(this string source, string toCheck, StringComparison comp)
       {
           return source.IndexOf(toCheck, comp) >= 0;
       }
   }
}

Without static class, your extension method won't work.

After you put the above in a .cs file, you can not use String.Contains anywhere since almost all code use System namespace, which means it is kinda global ;)

like image 191
Amit Joki Avatar answered May 21 '23 07:05

Amit Joki