Being a bit of a purist, I hate seeing string constants spread through out my code:
var x = element.Attribute("Key");
I like to have the them stored as a single referenced constant, and I like the approach I first saw in Eric White's 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 of this is that I can easily find all references to these static
fields using Visual Studio or Resharper and not have to wade through each found instance of the string "Key", which one can imagine is used in many unrelated places.
So, I have a legacy project that I want to convert to using the XName
approach and need to find all occurrences of where a string has been used instead of an XName
. I figure that if I could stop the automatic conversion of string to XName
, the compiler would pick up all these occurrences for me.
I used a regex in the find:
(Element|Attribute|Ancestor)s?\("
which picked up those constructs, but then I found:
if (element.Name == "key")
and wondered what else I was going to miss.
The question is, how do I stop the automatic conversion of string to XName
, or what other approach is there to locating all occurrences of string that should be XName
?
Implicit operators can't be stopped.
In the other hand, taken from MSDN:
XName does not contain any public constructors. Instead, this class provides an implicit conversion from String that allows you to create an XName
Alternatively, you could turn this code:
if (element.Name == "key")
...into:
XName key = "key";
if(element.Name == key)
BTW, I feel that you're going to overcomplicate things just to get more searchability, while the goal of coding programming languages is producing executable code and you should code as simple as possible to increase maintainability and quality...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With