Why can't a string be default-constructed?

A

Andreas Huber

Hi there

Can anyone imagine a reason why string does not have a default ctor?

Agreed, that might be necessary only very rarely in .NET 1.1 code.
However, in conjunction with .NET 2.0 and generics it is just plain
annoying. Example:

class Param< T > where T : new()
{
public Param()
{
val = new T(); // here
}

// Other members

private T val;
}

Of course I would want to instantiate the Param template with all kinds
of types, e.g. double, int, and - you guessed it - string.

Thanks & Regards,
 
M

Mattias Sjögren

Can anyone imagine a reason why string does not have a default ctor?

What good would such a string do you, and what would its value be
(String.Empty?)

Can't you use default(T) for the initialization instead?



Mattias
 
A

Andreas Huber

Mattias said:
What good would such a string do you,

Well, no matter with what type I instantiate the generic class, I want
the T member to be default constructed. Assigning null to a
reference-type is definitely not an option.
While I agree that some types cannot be meaningfully default
constructed, I don't think System.String is one of them.
and what would its value be
(String.Empty?)

"" (String.Empty == true), what else?
Can't you use default(T) for the initialization instead?

No, that would assign null.

Regards,
 
C

cody

You are the second guy today in this newsgroup who is asking for a
parameterless constructor for System.String :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top