Hans
Hans

Reputation: 353

Pass on variable to set in C#

I want a pass several variables to a function to and set them to something else instead of reading from them. I am planning to use this in a scenario where i can create a object, and add it to a execution queue. Would a pointer be right for this?

I am aware my question has a poor explanation, but I don't know a better way to explain it.

Upvotes: 1

Views: 203

Answers (2)

Dave New
Dave New

Reputation: 40002

Are these variables reference types or value types? If they are reference types then you can pass them into your function as per normal and then mutate its properties from there. If they are value types then you must use the ref keyboard.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500165

It sounds like you probably want a ref or out parameter. For example:

public static void SetVariables(out int x, ref int y)
{
    // Can't *read* from x at all before it's set
    x = 10;
    // Can read and write y
    y++;
}

public static void Foo()
{
    int setOnly;
    int increment = 5;
    SetVariables(out setOnly, ref increment);
    Console.WriteLine("{0} {1}", setOnly, increment); // 10 6
}

See my parameter passing article for more information.

Upvotes: 7

Related Questions