locked
Why conversion to String^ fails?

    Question

  • In the following code two calls to conversion to String^ fails:

    ref class s sealed { void fun(String ^) { } void foo() { fun("this"); //OK fun(ref new String("this")); //fails, cannot convert parameter 1 from 'const char [5]' to 'const wchar_t *' fun(L"this"); //OK

    auto str = L"this"; fun(str); //fails, cannot convert parameter 1 from 'const wchar_t *' to 'Platform::String ^' } };

    I am not able to understand why it fails.

    1. fun("this") is oK but not fun(ref new String("this"))? How literal "this" is converted to String ^ while calling fun("this")?

    2. In the second case what is the difference between fun(L"this") and fun(str)? In both cases, fun is called with const wchar_t *, then why it fails in the latter case?


    • Edited by John Rick Thursday, October 04, 2012 6:11 AM
    Thursday, October 04, 2012 6:10 AM

Answers

  • See String Construction in Strings (C++/CX)

    The compiler will automatically treat string literals used to construct a String^ as char16 where it can. The examples which work are doing this. The examples which fail are where we aren't constructing directly from the literal and so cannot infer its type (in the first failure) or perform a cast to String^(in the second failure).

    --Rob

    Friday, October 05, 2012 2:23 AM
    Owner