c# - Return a constant string array -


i created string[] getter information on class. want return same value, , not create new object on each call.

i have implemented this:

string[] _somestrings = { "foo", "bar" }; protected string[] somestrings {     {         return _somestrings;     } } 

which seem ok. however, first inkling write this:

protected string[] somestrings {     {         return { "foo", "bar" };     } } 

but doesn't work (i error ; expected).

why?

(this "getting-to-understand-c# question).

update made typo. not want create new object on each call.

the correct syntax this:

return new [] { "foo", "bar" }; 

the reason short syntax without new [] valid assignment.

as correctly note in comment, create new object on every call. way avoid field stores created instance , return field. solution have.
please note however, allows consumers change contents of array , affect other consumers:

var a1 = foo.somestrings; var a2 = foo.somestrings; a1[0] = "some other value"; assert.equal("some other value", a2[0]); // pass 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -