i know that string is like a class, and when creating a new string the string itself doesnt owe the value but only the value's pointer. but when creating a string there is no need to use the word new;
string a = "hello";
and not
string a = new string("hello");
I know that the second option is also possible but what i want to understand is why the first one?
Let's say I have a class name student which he's constructor gets a string
. To create a new class I must use the saved word new.
student example = new student("Sabrina");
I tried overload oparator =
but it is not possible.
How can I create a new class like a string
does (without using the word new
)?
student example = "Sabrina";
You can use cast operator to implicitly:
sealed class Student
{
public string Name
{
get;
private set;
}
Student()
{
}
public static implicit operator Student(string name)
{
return new Student
{
Name = name
};
}
}
Then you can do Student student = "Sabrina";
.
Although you can get this done using an implicit operator
, I would highly recommend not doing this at all. Strings
are special animals in C# and they get special treatment - along with other special classes like int
and float
, you can create them without explicitly new
ing them up due to the way the C# compiler works:
var myInt = 0;
var myFloat = 0f;
var myString = "string";
However, this behavior is typically restricted to those special classes. Adding an implicit operator
to do this is bad practice for multiple reasons:
new Student
under the hood when converting from a string
? Student
's ID number as well?var student = "name"
; you must call Student student = "name"
.The implicit operator
paradigm breaks down very quickly. Though it's a cool thing to do, you're setting yourself up for a bad time down the road and making your code more difficult to read. I would highly advise just using new Student("name")
like all other normal objects in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With