ScanIAm wrote:


There is a completely different thread about a slightly tangential topic, but I'm noticing a number of pieces of example code that concerns me.

I've done this myself, but how 'safe' is it:

Console.WriteLine(new String("Bob").Length);

The part that concerns me is the accessing of the function 'Length' when you don't really know that the new String has actually been created.

The other side of the coin, however, is that you could end up with twice as many lines of code if you check every single variable before using it.

What do you do?



First, your example is bad:

Console.WriteLine("Bob".Length);

However, the idea is there, so I'll address it.  The new String will either be created, thus no problem, or an exception will be thrown and so Length won't be called, so also no problem.  The only problems that exist here exist whether or not you "chain" the calls to the constructor.

Check the variable before using it?  Like I said, either it worked, and so there's no reason to check, or it threw an exception, so there's no reason to check.  I guess I don't get what you think the problem is?