Create a class that can be created as an XNamespace class

An XNamespace object can be created as follows:

XNamespace ns="http://www.xyz.com"; 

Here the line " http://www.xyz.com " is interpreted as the value of the property (NamespaceName) of this class. I was wondering if I can create such a custom class where it can simply be created in this way. The syntax really looks pretty cool.

+4
source share
2 answers

You just need to add the implicit conversion operator from the string:

 public class Foo { private readonly string value; public Foo(string value) { this.value = value; } public static implicit operator Foo(string value) { return new Foo(value); } } 

I would use this with caution, although this makes it less obvious what happens when reading the code.

(LINQ to XML makes all kinds of things β€œa bit dubious” in terms of API design ... but manages to get away from it because it all fits together so neatly.)

+3
source
 class MyClass { public string Value {get; private set;} public MyClass(string s) { this.Value = s; } public static implicit operator MyClass(string s) { return new MyClass(s); } } 

Now you can:

 MyClass myClass = "my string"; Console.WriteLine(myClass.Value); //prints "my string" 

Note that XNamespace also supports the add statement , which takes strings as the correct parameter. This is a good API solution if you are dealing with strings. To implement this, you can also overload the addition operator:

 //XNamespace returns XName (an instance of another type) //but you can change it as you would like public static MyClass operator +(MyClass val, string name) { return new MyClass(val.Value + name); } 
+5
source

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


All Articles