Well, the second form is illegal, unless a conversion operator has been defined.
To implement this conversion operator, you will have to use new MyClass
to construct a new instance.
So provided the second form is legal at all, the method and end result is the same.
Example of conversion operator:
public class MyClass
{
public static implicit operator MyClass(string s)
{
return new MyClass();
}
}
Note that this conversion operator also handles this line:
a = "something";
Which simply overwrites the original reference stored in a
with the new one returned by the conversion operator.
A conversion operator defines a static method named op_Implicit
(in this case) that will be called, so your code really looks like this under the hood:
MyClass a = new MyClass();
a = MyClass.op_Implicit("something");
or this:
MyClass a = MyClass.op_Implicit("something");
You can verify this using LINQPad if you can read IL.
This code:
void Main()
{
MyClass a = "something";
a = "xyz";
}
Translates to this IL:
IL_0000: nop
IL_0001: ldstr "something"
IL_0006: call UserQuery+MyClass.op_Implicit
IL_000B: stloc.0 // a
IL_000C: ldstr "xyz"
IL_0011: call UserQuery+MyClass.op_Implicit
IL_0016: stloc.0 // a
IL_0017: ret
Note the two calls to op_Implicit
.
Now, if you don't implement the conversion operator then:
MyClass a = new MyClass();
a = "something" // error
MyClass a = "something"; // error
The error message will in both cases be:
CS0029
Cannot implicitly convert type 'string' to 'MyClass'