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.
The String(Char[]) constructor copies all the characters in the array to the new string. The String(Char[], Int32, Int32) constructor copies the characters from index startIndex to index startIndex + length - 1 to the new string. If length is zero, the value of the new string is String.
1. String(): To create an empty String, we will call the default constructor. The general syntax to create an empty string in java program is as follows: String s = new String();
In the Java programming language, strings are objects. The String class has over 60 methods and 13 constructors.
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.
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