C# Array of references to Variables and or Form objects

c# initialize array of objects
c# array of arrays
c# new array
add items to string array dynamically c#
single dimensional array in c#
array program in c# console application
types of arrays in c#
c# reference variable

What I am trying to do is to have an array of references to variables. By which I mean the equivalent to a C array of pointers to ints (for example).

Example: (!!not real code!!)

int a = 4;
int b = 5;
int c = 6;
List<ref int> tmp = new List<ref int>();

tmp.Add(ref a);
tmp.Add(ref b);
tmp.Add(ref c);

tmp[0] = 16;
tmp[1] = 3;
tmp[2] = 1000;

Console.Writeline(tmp[0] + " " + a); // 16 16
Console.Writeline(tmp[1] + " " + b); // 3 3
Console.Writeline(tmp[2] + " " + c); // 1000 1000

The specifics of my case: I have a list of strings that will correspond to the keys in a dictionary. What I think I want to have is a list of Tuples where Type1 is a reference to either an int or string, and Type2 is a reference to an Textbox.

I will be iterating through this list, using the string to get the value from the dictionary (and doing stuff with that data) then storing the results of that into Type1. And eventually I will be taking the data from those Type1 variable references and copying their data to the corresponding Type2 Textbox.

That's the gist of what I think I want to do. If someone thinks that my approach is overly complicated, I will say that I need to keep the Textboxes as they are sadly, so I can't just make an array and iterate through it. And it would be perferable to keep the Type1 variables seperate too, though not quite as necessary.

Now, from reading around, I thought Func<> looked like it was the closest thing to being useful for what I want, so I tried to use the following (with Type1, as an object because it needs to handle both ints and strings)

List<Tuple<string, Func<object>, Func<object>>>

but I was unsure how to use that to get references to the variables.


What you're specifically asking for isn't possible; what would be more appropriate (and has the convenience of actually working!) would be to design a class structure around what you're trying to do.

For instance, something like this:

public class MyObject // Name it appropriately
{
    public object Value { get; set; }
    public string Key { get; set; }
    public TextBox TextBox { get; set; }
}

Then, in your code, you can do something akin to this...

Dictionary<string, object> values = ...
List<MyObject> objects = ...

foreach(var item in objects)
{
    item.Value = values[item.Key];

    // process your data

    item.TextBox = item.Value.ToString();
}

Obviously, this is just a rough design and the class here serves as little more than a data transfer container. You could make the class "smarter" by, for example, using the setter for the Value property to set the value of the TextBox automatically. But this should hopefully give you the general idea of how something like this would be done in an OO fashion.

EDIT Here's how your example would look.

MyObject a = new MyObject() { Value = 4 };
MyObject b = new MyObject() { Value = 5 };
MyObject c = new MyObject() { Value = 6 };
List<MyObject> tmp = new List<MyObject>();

tmp.Add(a);
tmp.Add(b);
tmp.Add(c);

tmp[0].Value = 16;
tmp[1].Value = 3;
tmp[2].Value = 1000;

Console.Writeline(tmp[0].Value.ToString() + " " + a.Value.ToString()); // 16 16
Console.Writeline(tmp[1].Value.ToString() + " " + b.Value.ToString()); // 3 3
Console.Writeline(tmp[2].Value.ToString() + " " + c.Value.ToString()); // 1000 1000

ref keyword, The ref keyword indicates a value that is passed by reference. caller's local variable or the array element now refers to the new object when This differs from out parameters, whose arguments do not have to be explicitly  Passing arrays as arguments in C#. An array is a collection of similar type variables which are referred to by a common name. In C#, arrays are the reference types so it can be passed as arguments to the method. A method can modify the value of the elements of the array.


You can't store references using C#. You can only use the ref keyword when calling a method.

You can use pointers, but you can only do that with a fixed expression and within an unsafe context.

It is possible to fake this kind of thing using delegates, but I'm not sure if it's what you're looking for. I'm also fairly sure that you really need to redesign your approach, but nevertheless, here's an example of how you can fake it...

Firstly, write a "value wrapper" class like so:

public class ValueWrapper<T>
{
    readonly Func<T>   get;
    readonly Action<T> set;

    public ValueWrapper(Func<T> get, Action<T> set)
    {
        this.get = get;
        this.set = set;
    }

    public T Value
    {
        get
        {
            return get();
        }

        set
        {
            set(value);
        }
    }
}

Then you can use that to change values:

void run()
{
    int x = 0;

    var intWrapper = new ValueWrapper<int>(() => x, value => x = value);

    test(intWrapper);

    Console.WriteLine(x);  // Prints 42, which shows that x was changed.

    TextBox textBox = new TextBox {Text = ""};

    var stringWrapper = new ValueWrapper<string>(() => textBox.Text, value => textBox.Text = value);

    test(stringWrapper);

    Console.WriteLine(textBox.Text); // Prints "Changed".
}

static void test(ValueWrapper<int> wrapper)
{
    wrapper.Value = 42;
}

static void test(ValueWrapper<string> wrapper)
{
    wrapper.Value = "Changed";
}

You can also create a wrapper in one method and pass it to a different method which uses the wrapper to change a property in the original wrapped object, like so:

void run()
{
    TextBox textBox = new TextBox {Text = ""};

    var wrapper = test1(textBox);
    test2(wrapper);
    Console.WriteLine(textBox.Text); // Prints "Changed"
}

void test2(ValueWrapper<string> wrapper)
{
    wrapper.Value = "Changed";
}

ValueWrapper<string> test1(TextBox textBox)
{
    return new ValueWrapper<string>(() => textBox.Text, value => textBox.Text = value);
}

Warning: This does lead to some fairly head-scratching code, for example:

void run()
{
    var intWrapper = test();
    intWrapper.Value = 42;
    Console.WriteLine(intWrapper.Value); // Works, but where is the value? It can't be the x inside test()!
}

ValueWrapper<int> test()
{
    int x = 0;
    var intWrapper = new ValueWrapper<int>(() => x, value => x = value);
    return intWrapper;
}

So we returned a ValueWrapper from test() which is apparently wrapping a local variable from inside test(). And then we can apparently change the value and print it out...

This isn't really what's happening, of course, but it can be quite confusing!

C# Types and Variables, With reference types, it's possible for two variables to reference the Instead, array types are constructed by following a type name with square brackets. Every type in C# directly or indirectly derives from the object class  All array types are implicitly derived from System.Array, which itself is derived from System.Object. This means that all arrays are always reference types which are allocated on the managed heap, and your app's variable contains a reference to the array and not the array itself.


you can use pointers in this case, use unsafe keyword for method and set project unsafe to allow pointers in c#, also you can encapsulate the value in a class and in C# each class is of reference type

Passing Reference-Type Parameters, A variable of a reference type does not contain its data directly; it contains a reference to arr , it is possible to change the values of the array elements. to change the contents of an array element, in this case from 1 to 888 . Passing Reference-Type Parameters (C# Programming Guide) A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data belonging to the referenced object, such as the value of a class member.


i used this and works perfect:

exp.

public int value1 = 3;
public int value2 = 4;
public int value3 = 5;

public void Method1()
{
    int[] values = { value1, value2, value3};
    for (int i = 0; i < values.Length; i ++)
    {
        Console.WriteLine(values[i]);
    }
}

Arrays, You can store multiple variables of the same type in an array data structure. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. However, as strings are immutable objects you can only use the references to read the items. If you assign a string to a reference in the sr array, you will overwrite the reference instead of changing the object that it points to. If you want to change the objects, you will have to have mutable objects. For example:


Ref return values and ref locals (C# Guide), The output from the example shows the change reflected in the value of the array elements of the NumberStore instance. C# Copy. var store =  Types and variables. 04/24/2020; 5 minutes to read +6; In this article. There are two kinds of types in C#: value types and reference types.Variables of value types directly contain their data whereas variables of reference types store references to their data, the latter being known as objects.


Passing Parameter Arrays By Reference, By default, IDL arrays are passed to and received from the COM subsystem “by “by reference” array passing, which passes an IDL array to a COM object in such a variable to make sure it is a pointer to an array, and that the destination COM When implementing a COM-callable class in C# and passing in an array of  Class employees is a nullable type, which means arrays made of it are initialized to nulls. Initialize emp[count] to new employees. BTW, "employees" is a strange name for a class that holds a single employee. I think it should be called Employee, then it makes sens to declare your array like this: `Employee[] employees = new Employee[emp_count];`


Value Type and Reference Type, This article explains Value Types and Reference type in C#. ValueType, which in-turn, derives from System.Object. For example, consider integer variable int i String; All arrays, even if their elements are value types; Class; Delegates  All array types are implicitly derived from System.Array, which itself is derived from System.Object. This means that all arrays are always reference types which are allocated on the managed heap, and your app's variable contains a reference to the array and not the array itself.