In C# we can write
Int a=new int();
char a=new Char();
person p=new person();
where person is a Class.
So why can't we write
string s =new string();
After all string is a reference type. Then why it's not possible?
In C# we can write
Int a=new int();
char a=new Char();
person p=new person();
where person is a Class.
So why can't we write
string s =new string();
After all string is a reference type. Then why it's not possible?
You can not write it because string
has not Constructor taking 0 parameters.
Instead you can write something like this:
String a = new string(new char[]{});
int and char are primitive types. In C#, they are really just aliases for the Int32 and Char classes. These classes have constructors with no parameters. In the case of your Person() class, it also has a constructor with no parameters if your code compiles. Strings are a bit different. Here is the list of valid String constructors according to MSDN: https://msdn.microsoft.com/en-us/library/system.string.string(v=vs.110).aspx
Personally, I generally just use something along the following if I want to explicitly initialize a String without going through the process of using a constructor mentioned above:
String testStr = String.Empty;
Which is really the same as:
String testStr = "";
It would be pointless to use the constructor to create a new string based on another existing string - that's why there is no constructor overload that allows this. Just do
string s = "String in a C#";
When you create a reference type (for example a class), you can choose what constructors it will have (for value types a parameterless constructor is required, so your choice is limited). If you do not specify any, then a default parameterless constructor is created for you implicitly. The C# designer team decided that it is not worth having a parameterless constructor on the String
type. That's why you cannot call new string()
. That's all there is to it.
You can do the same with your custom class.
public class C
{
public C(int i)
{
}
}
var c = new C(); // invalid