Can I prevent automatic casting from a string in XName?

Being a bit of a purist, I hate to see string constants propagated through my code:

var x = element.Attribute("Key"); 

I like them to be saved as one constant referenced, and I like the approach I first saw in Eric White XmlPowerTools :

 public class MyNamespace { public static readonly XNamespace Namespace = "http://tempuri.org/schema"; public static readonly XName Key = Namespace + "Key"; } 

and use:

 var x = element.Attribute(MyNamespace.Key); 

The beauty is that I can easily find all the links to these static fields using Visual Studio or Resharper, and I don’t have to go through every found instance of the β€œKey” line that I can imagine, it is used in many unrelated places.

So, I have an old project that I want to convert to an XName method, and you need to find all the occurrences where the string was used instead of XName . I believe that if I could stop the automatic conversion of the string to XName , the compiler would pick up all these occurrences for me.

I used regex in the search:

 (Element|Attribute|Ancestor)s?\(" 

who took these constructs but then found:

 if (element.Name == "key") 

and thought what else would I miss.

The question is how to stop the automatic conversion of a string to XName or what other approach to find all occurrences of a string, which should be XName ?

+6
source share
2 answers

So, you can fix this, but not prevent it (without packaging the XName library).

Remove the XName library XName , create your own XName class with the same namespace, but do not provide an implicit string conversion. Try compiling and you will find all the places where the string is assigned to XName .

You may need to play with it in order to compile correctly (for example, cut your new class into a separate library, having it, and only it refers to the XName library and subclasses the original, so it does not fail to compile when using the object in the API).

Once you fix everything, delete the class and add the XName library back.

To prevent this in the future, you can write a class that provides implicit conversion to XName, but not from a string. However, unfortunately, you will need to modify your entire code base in order to use your wrapper.

0
source

Implicit statements cannot be stopped.

On the other hand, taken from MSDN :

XName does not contain public constructors. Instead, this class provides an implicit conversion from String that allows you to create XName

Alternatively, you can include this code:

 if (element.Name == "key") 

... in:

  XName key = "key"; if(element.Name == key) 

By the way, I feel that you will be too complicated to get more search capabilities, while the goal of coding programming languages ​​is creating executable code, and you should code as simple as possible to increase maintainability and quality ...

+1
source

All Articles