C#: change actual value in function (not for JS coders)

Hi programmers,

  1. Wanna use it like that:
transform.position.SetX(-100);

public static class Vector3Extender
{
	public static void SetX(this Vector3 vector, float x)
	{
		vector.Set(x, vector.y, vector.z);
	}
}
  1. But forced to use it like that:
transform.position = transform.position.SetX(-100);

public static class Vector3Extender
{
	public static Vector3 SetX(this Vector3 vector, float x)
	{
		vector.Set(x, vector.y, vector.z);
		return vector;
	}
}

For example, in C++ I could use reference operator, but now I don’t know what to do here.

Thank you!

i don’t fully understand what you want, ref?:

SetX(ref Vector3 vector3; float x){
 vector3 = new Vector3(x, vector3.y,vector3.z);
}

//call it like that
SetX(ref transform.position, -100);

untested :F

Edit: now i understand, you want a static method… i cant help you though :confused:

C# has the same reference concept as C++, its by using the “ref” keyword: http://msdn.microsoft.com/en-us/library/14akc2c7(v=vs.71).aspx

Thank you!

As far as I know, C# doesn’t allow using “ref” on “this” parameters in extension methods.

Another pitfall is that transform.position is a property. So, even if you manage to modify the value, you will only modify it’s copy, leaving the real value underneath the property unchanged.

Dmitry is right; ref and out don’t work with extension methods. How about

public static void AdjustPosition(this Transform transform, float? x = null, float? y = null, float? z = null) {
	Vector3 position = transform.position;
	transform.position = new Vector3(x ?? position.x, y ?? position.y, z ?? position.z);
}

?

transform.AdjustPosition(x: -100);

Edit: I thought I had done that before. I like the syntax here better.

Thank you!

Just gotta say, Vector3.Set sucks. Worst parameter names ever!