A
A
antonwx2021-10-16 13:17:31
C++ / C#
antonwx, 2021-10-16 13:17:31

How to set the return value of a method in C# (.NET) via ref using reflection?

There is something like this code:

private ref int GetRefValue(int code)
        {
            //blah blah
            return ref something;
        }

In a normal way, it is called like this:
this.GetRefValue(code) = value;
And how to call it through reflection?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris the Animal, 2021-10-16
@antonwx

using System;
using System.Diagnostics;
using System.Reflection;

namespace ConsoleApp
{
    class Program
    {
        private delegate ref int GetMaxNumber(ref int value1, ref int value2);

        static void Main(string[] args)
        {
            int value1 = 5;
            int value2 = 10;
            var instance = new Something();

            MethodInfo? methodInfo = typeof(Something).GetMethod(
                nameof(Something.GetMax), BindingFlags.Public | BindingFlags.Instance);
            Debug.Assert(methodInfo is not null);
            var setNumber = (GetMaxNumber)Delegate.CreateDelegate(typeof(GetMaxNumber), instance, methodInfo);

            setNumber.Invoke(ref value1, ref value2) = 50;

            Console.WriteLine($"{nameof(value1)}: {value1}, {nameof(value2)}: {value2}");
        }
    }

    public class Something
    {
        public ref int GetMax(ref int left, ref int right)
        {
            if (left > right)
            {
                return ref left;
            }

            return ref right;
        }
    }
}

Checked on
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question