0

I want to set a variable value with the extension method for development purposes. There is a preprocessor instruction that runs in the dev environment and I want to have an option to test value in the shortest way while developing stuff. I plan to apply this to any generic type, assuming I know the types I work with, although type check wouldn't hurt.

So I try this extension method:

 public static object ToEditorValue(this object value, object newValue)
 {
    #if UNITY_EDITOR
        value = newValue;
    #endif
        return value;
 }

And calling it like this does the job:

myInt = (int)myInt.ToEditorValue(2);

So the question is there a way to make the extension method so the calling one is minimal as

myInt.ToEditorValue(2);
JohnyL
  • 6,894
  • 3
  • 22
  • 41
Madcode
  • 81
  • 1
  • 7
  • 1
    So the real question is how to avoid the cast? Don't use `object`. As for `does the job` not really - `myInt` is never modified. – Panagiotis Kanavos Jun 18 '21 at 19:05
  • no, the real question is stated in the original message. What if I want to apply this to string? – Madcode Jun 18 '21 at 19:06
  • What *is* the real question?`value` isn't a variable, it's a parameter. The extension method doesn't change that parameter, it only returns the new value boxed as an object. If you used `int` instead of object you wouldn't need a cast. Besides, what's the point of this method? Why not just write `myInt=2`? – Panagiotis Kanavos Jun 18 '21 at 19:08
  • 1
    So basically you are asking: [Impossible to use ref and out for first ("this") parameter in Extension methods?](https://stackoverflow.com/q/2618597/7111561) – derHugo Jun 18 '21 at 19:10
  • If the method did something other than return the input, you could avoid boxing by making it generic, ie `static T ToEditorValue(this T source, T value){ .....; return value;}` – Panagiotis Kanavos Jun 18 '21 at 19:12
  • @PanagiotisKanavos `Besides, what's the point of this method? Why not just write myInt=2` .. the idea of OP is to generelize and not everytime having to use the preprocessors for all fields and values in different classes but rather have one general way to decide whether the editor specific or the original value should be used ;) ... I also think a generic is the most closest you will get @OP – derHugo Jun 18 '21 at 19:16
  • 1
    @derHugo that's not generalization. That's setting a mine for other developers that won't be able to tell what this method actually does. If `UNITY_EDITOR` is not set, `newValue` is never used – Panagiotis Kanavos Jun 18 '21 at 19:17
  • @PanagiotisKanavos which doesn't matter at all though .. this is what OP wants for him and his project .. let him to that. Other devs are one single click away from seeing what the method does or if OP adds proper XML comments one mouse over .. so what is the issue? ;) – derHugo Jun 18 '21 at 19:20

0 Answers0