Reputation: 197
I want to create a string that consists of a single character such as '\t' and that's it, however the String class constructor won't accept it.
String myTab = new String( '\t' );
This gave me:
Error 2 Argument 1: cannot convert from 'char' to 'char*'
Okay, I thought I wouldn't need pointers after switching from C++, but I'll give you one then:
char oneChar = '\t';
String myTab = new String( &oneChar );
Gives:
Error 1 Pointers and fixed size buffers may only be used in an unsafe context
So I tried this clumsy conversion instead without success:
String myTab = new String( ToString('\t') );
The error I get here is:
Error 3 Argument 1: cannot convert from 'string' to 'char[]'
This is the simplest issue ever and it irritates me a lot. Can anybody tell me how to solve it and why the string class isn't made to accept single characters?
Upvotes: 0
Views: 366
Reputation: 74277
You can do what you want in a number of ways. Just off the top of my head, that includes (but probably isn't limited to):
string s1 = '\t'.ToString() ;
string s2 = new string( new char[]{'\t'} ) ;
string s3 = new string( '\t' , 1 ) ;
string s4 = new StringBuilder().Append('\t').ToString() ;
Or, since you already know the character in question:
string s5 = "\t" ;
I suspect that all of the 1st 4 will likely be optimized away into the 5th form.
Upvotes: 0
Reputation: 120480
char
and string
are different data types. You can't use a char
where a string
is expected (or for that matter, where a char*
or char[]
are expected).
The constructor that takes char*
can only be used in an unsafe
context (see other answers), but unless you've got a real good reason for going unsafe
, don't do it (however tempting it is with your C++ background).
'\t'
defines a char
"\t"
defines a one character string
As such wouldn't
string myString = "\t";
be fine?
If you want to convert a char
into a string
string myString = myChar.ToString();
Upvotes: 7
Reputation: 65079
While spender's answer addresses your main issue, I thought I might answer your issue with the pointer.
The error Pointers and fixed size buffers may only be used in an unsafe context
means that you need to tell the compiler you're using potentially unsafe code, by wrapping it in an unsafe
block:
unsafe {
char oneChar = '\t';
String myTab = new String( &oneChar );
}
..would then be fine.
But, you also need to let the compiler know that you're going to be using unsafe code by enabling it in the project settings:
Upvotes: 1
Reputation: 61349
You don't normally "instantiate" a string object, and you certainly don't assign a string to a char.
The following will compile:
String test = "\t";
This is the normal way of doing what you ask.
Upvotes: 2