Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set variable in helper method and it changes in parent scope. #2413

Closed
mekb-turtle opened this issue Apr 10, 2019 · 4 comments
Closed

Set variable in helper method and it changes in parent scope. #2413

mekb-turtle opened this issue Apr 10, 2019 · 4 comments

Comments

@mekb-turtle
Copy link

mekb-turtle commented Apr 10, 2019

So I was wondering if it's possible to set a variable in a helper method for example:

public static void SetX(this Point a, int val) {
    a = new Point(val, a.Y);
    // Will `a` change in the place where this function is called from?
}

If this is not possible, can you recommend an alternative solution?

@Joe4evr
Copy link
Contributor

Joe4evr commented Apr 10, 2019

Just mark the Point parameter to be passed by ref.

Side note: you should follow standard conventions and name your methods in PascalCase.

@marksmeltzer
Copy link

@Joe4evr

Dumb question: is that possible for extension methods? I've never tried on the assumption it isn't possible.

@PathogenDavid
Copy link

@marksmeltzer

Yup, it was added in C# 7.2, although only for structs.

Here's an example of it in action.

@mekb-turtle
Copy link
Author

Just mark the Point parameter to be passed by ref.

Side note: you should follow standard conventions and name your methods in PascalCase.

I thought is was lowerCamelCase and UpperCamelCase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants