Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String constructor

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 strings? And for enums?

I've never seen an explanation of how this works.

like image 730
radders Avatar asked Jun 13 '14 13:06

radders


People also ask

Does string have a constructor?

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.

How do you call a string constructor in Java?

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();

How many string constructors are there in Java?

In the Java programming language, strings are objects. The String class has over 60 methods and 13 constructors.


1 Answers

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.

like image 82
Jon Skeet Avatar answered Oct 14 '22 11:10

Jon Skeet