Why can't a string be default-constructed?

  • Thread starter Thread starter Andreas Huber
  • Start date Start date
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,
 
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
 
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,
 
You are the second guy today in this newsgroup who is asking for a
parameterless constructor for System.String :)
 
Back
Top