0

I'm currently writing lab work for my study, and I'd like to make a function return a pointer to the variable from the same class.

int* getProc(int id)
    {
        switch (id)
        {
            case 1:
                return &this.proc1tasks;
                break;
            case 2:
                return &this.proc2tasks;
                break;
        }
    }

But for every &this.proc#tasks VS 2013 says

Error 2 Pointers and fixed size buffers may only be used in an unsafe context

Is there any way to make it work as I imagined?

7
  • The error message tells you exactly what you need to do: go read about the unsafe keyword. Commented Feb 18, 2015 at 18:41
  • 5
    Yes. Use an unsafe context, as the error message indicates. More to the point though is why do you want to do this? There are alternatives that would work in safe code, but without more context it's not practical to try to guess what you really want. Commented Feb 18, 2015 at 18:42
  • Actually, I have five such variables in this class and based on the function parameter I wanted to return pointer to one of that variables to use it in further operations. Will it work if I enable unsafe code in project settings? And as far as I understand unsafe must be always used when I use pointers in C3 code? Commented Feb 18, 2015 at 18:48
  • 1
    You just don't want to actually use pointers here; you want to use managed constructs to accomplish a goal that you would normally use pointers for in another language like C/C++. Commented Feb 18, 2015 at 18:52
  • 1
    I'd like to make a function return a pointer That may be true. But do you like to because you actually need it or do you just think it is the way because you don't know about regular C#/.NET programming?? Commented Feb 18, 2015 at 18:58

1 Answer 1

4

Have the method return a delegate that, when invoked, will evaluate the value of the variable in question:

public Func<int> getProc(int id)
{
    switch (id)
    {
        case 1:
            return () => proc1tasks;
        case 2:
            return () => proc2tasks;
    }
}

This will provide you with an object which, when invoked (much like with a pointer you would dereference), will give you the current value of that field.

Sign up to request clarification or add additional context in comments.

1 Comment

I like this much better than the unsafe way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.