new or not new

  • Thread starter Thread starter Jay
  • Start date Start date
J

Jay

Why is it some things require new and some do not?

System.String name;

System.Random r = new Random
 
Those both require new.
Your definition of name will result in a string variable with a null value.
 
Jay,

new operator calls the default constructor of the specific type and assigns
the default value to the variable. In c# local variables must be initialized
before using that.

In case of Value types the default values are returned by default
constructors. Instead of declaring

double mybool = new double();

you can say

double mybool = 0.0; //which is a default value.

Shak.
 
System.String has constructors. It's just syntax sugar that you don't
generally have to new us a String directly. It is done implicitly for you
as a convenience.

Actually the only time I've ever used the String constructor directly is to
create a string preloaded with a number of characters:

string strTwentySpaces = new String(' ',20);

--Bob
 
Thank You for the reply.

My question now is how many bytes are allocated with the following:

string name; <--how many here

as opposed to

string name = new String(' ',20); I'm assuming 20 bytes and 1 for the
null

Is it 255 bytes or not determined until there is an assignment with either
readline or direct assignment?

Thank You!
 
Jay said:
My question now is how many bytes are allocated with the following:

string name; <--how many here

as opposed to

string name = new String(' ',20); I'm assuming 20 bytes and 1 for the
null

No, about 56 I believe. Characters in .NET are Unicode, and IIRC
strings take up 12 bytes (header+string length) +
((number of characters+1 for the nul) rounded up to an even number) * 2

(Just before anyone says that strings aren't null-terminated in .NET -
they aren't as far as the API is concerned, but they are in memory,
presumably for interop reasons.)
Is it 255 bytes or not determined until there is an assignment with either
readline or direct assignment?

Just declaring the variable doesn't instantiate a string at all. It'll
take basically 4 bytes - the size of the variable itself.
 
Back
Top