I have a generic method where I want to do something special for Strings.
I’ve found DirectCast(DirectCast(value, Object), String) to get the String value (when I’ve already confirmed GetType(T) Is GetType(String)) and DirectCast(DirectCast(newvalue, Object), T) as mentioned in a number of answers to similar questions works.
But is there anything more elegant and is it performant?
There’s one simpler option in this particular case: call
ToString()on the value. For a string, this will just return the original reference.In the general case, you do need to convert up to object and down again, which is unfortunately pretty ugly. In terms of performance, I’d be pretty surprised to find that this is the bottleneck anyway – but I suspect the
ToString()call is as efficient as anything else.