-3

Friends, can anyone introduce a Generic Extension Method by which the value of any variable or object can be changed?

Similar to this method:

public static void Set<T>(this T source, T value)
{
    // some code (source = value)
}
Farzad
  • 93
  • 2
  • 10
  • 1
    What are you hoping to accomplish with that? It might be confusing to change a variable with an extension method – Daniel A. White Jan 21 '22 at 13:15
  • 3
    you cannot change value of source in such a way it is visible from outside you would need to have ref parameter for that and that blocks the extension method requirement – Rafal Jan 21 '22 at 13:22
  • This means that there is no way to implement with Reflection and have this code? **var n = 0; n.Set(1);** – Farzad Jan 21 '22 at 13:29
  • No, because you can only **modify** an instance by an extension-method, not **change its reference**. `0` and `1` are completey different int-instances. Why do you need that? Seems pretty odd to me. What is your actual *goal* here. Not what you think the solution might be. – MakePeaceGreatAgain Jan 21 '22 at 13:30
  • what about a normal static method: `static void Set(ref T source);`. Now you should be able to call it like `ExtensionClass.Set(ref myInstance);` However if you want to change a reference, why not just use `myInstance = new Whatever(...)`? In your example that'll be `var n = 0; n = 1`. – MakePeaceGreatAgain Jan 21 '22 at 13:33
  • The problem was implementing a Generic method and feasibility of doing it with Reflection, and I can say I got the answer, thank you. – Farzad Jan 21 '22 at 13:39
  • This was a challenge on Reflection and Generic and I was required to research it, thanks for your response. – Farzad Jan 21 '22 at 14:03

1 Answers1

1

What you want is impossible, as an extension-method allways works on a specific instance of a type. As every other method as well, a method can not change the instance to be something different (which would mean reference another instance), it can only modify that instance by calling any of its members.

If you want to know why it is forbidden to use ref on an extension-method, look this similar question: Impossible to use ref and out for first ("this") parameter in Extension methods?.

On the other hand you can do that with normal methods using the ref-keyword, though.

public static void Set<T>(ref T instance)
{
    instance = new Whatever(...);
}

Now you may be able to use this:

var n = 0;
TheClass.Set(ref n);

However if all you want to do in that method is replacing one reference by another one, why not just use this instead?

var n = 0;
n = 1;
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Yes, I did not want to twist the story But my problem was about Reflection and Generic, thank you. – Farzad Jan 21 '22 at 13:57