We can say,
string myString = "Hello";
Which 'magically' constructs a new string object holding that value.
Why can't a similar 'construction-less' approach be used for objects created from classes we define in our code? What's the 'magic' that VS does for string
s? And for enum
s?
I've never seen an explanation of how this works.
Basically, it's part of the C# language specification: there's syntax for string literals, numeric literals, character literals and Boolean literals, but that's all.
The compiler uses these literals to generate IL, and for most of them, there's a suitable instruction for "constant of a particular type", so it's directly represented. One exception to this is decimal
, which is not a primitive type in terms of the CLR, and so has to have extra support. (That's why you can't specify a decimal
argument when applying an attribute, for example.)
The simplest way to see what happens is to use ildasm (or a similar tool) to look at the IL generated for any specific bit of source code.
In terms of creating your own classes - you could provide an implicit conversion from string
(or something else) to your own type, but that wouldn't have quite the same effect. You could write source code of:
MyType x = "hello";
... but that wouldn't be a "constant" of type MyType
... it would just be an initializer which happened to use your implicit conversion.
See more on this question at Stackoverflow