If you look at the documentation for the
String Class[
^]
you will see that there is no constructor that takes 0 arguments, hence the first compiler error.
The first line works because the literal string
"Code Project"
is treated as a constant by the compiler and stored on the heap in table.
Then the reference of that constant is assigned to the variable
s
.
See this link for more information about string storage.
String.Intern Method[
^]
To add assignment functionality to your own class, you need to add an implicit operator.
public static implicit operator Student(string s)
{
Student stud = new Student(s);
return stud;
}
= Operator (C# Reference)[
^]
implicit (C# Reference)[
^]
Of course you need to have a constructor in your
Student
class that takes a
string
as an argument.
If you have other data types that you want to assign like this, you just add one operator per type.