Basic
Basic

Reputation: 26766

Have a class behave like a string

Is it possible to have a class that behaves like a string but allows me to have some additional properties?

Specifically, I want to be able to do something like

Dim A As MyClass ''Or New MyClass("InitialValue")
A = "Something"
If A = "SomethingElse" Then

End If

From what I can see, I need to implement a type that can be assigned in such a way that it's passed the string in a constructor:

eg A = Something should be interpreted as A = New MyClass("Something"). In addition, I then need to override the comparison operator so that If A = "SomethingElse" Then can be handled by my code which checks the underlying String value

Since String is sealed/not inheritable and String seems to have some special handling in .Net I'm a little stumped as to how to approach this.

To explain why it's required, I've got an entity class (Not EF) which is serialized to generate queries against a search index. The queries are created by specifying a lambda against my entity.

I now need to modify certain properties on the entity so that instead of serializing to a simple string (for passing to the search index), they're complex objects. I don't have control over the serialization itself (currently being handled inside Newtonsoft Json.Net) so I was hoping this would be a (quicker) alternative which would allow me to use the existing lambdas, etc...

Upvotes: 3

Views: 346

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500065

You can do this for the assignment using a custom implicit conversion from System.String, as XNamespace does, for example1. Whether that would also work for the comparison, I'm not sure.

I'm generally very nervous of implicit conversions, and would urge caution around this. Having a constructor or static factory method, or possibly an extension method to convert from string to the relevant type, would make this clearer:

Dim A = new MyClass("Something")
If A = "SomethingElse".ToMyClass()

1 LINQ to XML contains a bunch of rule-breaking design decisions which make it easier to use. This is an example of genius being able to trump normal good practice - but most of us don't have that level of genius.

Upvotes: 3

Related Questions