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?



In an unsafe language like C that is absolutely correct:

#include <string.h>

int main(){
  int len;
  string b;

  b = (string)malloc(sizeof(char) * 3);
  strcpy(b, "Bob\0", 3);
  len = strlen(b);
}


Should have checks in it:


int main(){
  int len;
  string b;

  b = (string)malloc(sizeof(char) * 3);
  assert(b != NULL);
  strcpy(b, "Bob\0", 3);
  len = strlen(b);
}

In case you run your system down to the point where it can't allocate 3 bytes for you (heaven forbid).

In a language like C#, however, new is a memory safe operation, since if the internal malloc fails a new OutOfMemoryException() is thrown at the il line where the newobj instruction is.

There is no T such that
new T( args ...) === null

however, the line new T(args ... ) can throw an OutOfMemoryException if there is not enough system memory to allocate T on the stack.