views:

31

answers:

2

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?

+1  A: 

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.

Jon Skeet
That's what I get for offering the general question when I really only cared about the casting back to T :-)
Mark Hurd
A: 

I've now actually analysed the code with Reflector (but really only cared about the equivalent of the ILDASM output -- in fact the C# and VB.NET renderer doesn't display the cast to object in either direction):

DirectCast(DirectCast(value, Object), String) is compiled to

 box !!T
 castclass string

but DirectCast(DirectCast(newvalue, Object), T) is compiled to

 unbox.any !!T

So I am happy with that (seeing as I really only cared about the casting back to T, as I said in my comment to Jon Skeet's answer).

Mark Hurd