Search code examples
c#genericsreflectionextension-methods

Generic Extension Method for change value of any variable or object


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)
}

Solution

  • 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;