Get a string to reference another in C#

c#, string

Solution

The closest you can get is this:

unsafe
{
    string* a = &ArrayOfReallyVeryLongStringNames[439];     // no compile
}

Which gives an exception:

Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')

So no, not possible...

Also read this MSDN article which explains what types can be used (blittable types).

Problem

I'm coming from a C++ background. This question has been asked before, but try as I might I cannot find the answer. Let's say I have: ``` string[] ArrayOfReallyVeryLongStringNames = new string[500]; ArrayOfReallyVeryLongStringNames[439] = "Hello world!"; ``` Can I create a string that references the above (neither of these will compile): ``` string a = ref ArrayOfReallyVeryLongStringNames[439]; // no compile string a = &ArrayOfReallyVeryLongStringNames[439]; // no compile ``` I do understand that strings are immutable in C#. I also understand that you cannot get the address of a managed object. I'd like to do this: ``` a = "Donkey Kong"; // Now ArrayOfReallyVeryLongStringNames[439] = "Donkey Kong"; ``` I have read the Stack Overflow question Make a reference to another string in C# which has an excellent answer, but to a slightly different question. I do NOT want to pass this parameter to a function by reference. I know how to use the "ref" keyword for passing a parameter by reference. If the answer is "You cannot do this in C#", is there a convenient workaround? EDIT: Some of the answers indicate the question was unclear. Lets ask it in a different way. Say I needed to manipulate all items in the original long-named array that have prime indices. I'd like to add aliases to Array...[2], Array...[3], Array...[5], etc to a list. Then, modify the items in the list using a "for" loop (perhaps by passing the list just created to a function). In C# the "using" keyword creates an alias to a class or namespace. It seems from the answers, that it is not possible to create an alias to a variable, however.

Original source

Related problems