Wednesday, March 28, 2012

string.Format w/ const string

Could someone please explain why this is happening. I am using ASP.NET 1.1

I have a class called PaymentMessages, it contains a few public const string(s)

publicconststring SYS_NON_SUCCESS_MESSAGE_FORMAT_STRING = "{0}: AMOUNT: {1}, RETURN CODE: {2}";

when I call string.Format(PaymentMessages.SYS_NON_SUCCESS_MESSAGE_FORMAT_STRING, "FAIL", 550.00m, "22-e")
it throws an exception because PaymentMessages.SYS_NON_SUCCESS_MESSAGE_FORMAT_STRING evaluated to null. Why is this happening on const strings?

WORKS FINE:
string s = PaymentMessages.SYS_NON_SUCCESS_MESSAGE_FORMAT_STRING;
string.Format(s, "FAIL", 550.00m, "22-e")

Hi..

Here you are trying to manipulate const variable which is not possibe. Constants can only be value types rather than reference types.

If you want manipulate that string with out creating new string u can use static readonly which is both reference type and value type.

public static readonlystring SYS_NON_SUCCESS_MESSAGE_FORMAT_STRING = "{0}: AMOUNT: {1}, RETURN CODE: {2}";

Cheers

0 comments:

Post a Comment