Answer the question
In order to leave comments, you need to log in
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;
}
this.GetRefValue(code) = value;
Answer the question
In order to leave comments, you need to log in
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;
}
}
}
<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 questionAsk a Question
731 491 924 answers to any question