Home >Backend Development >C++ >How Can I Pass Properties by Reference in C#?
Passing properties by reference in C#
In C#, passing a property by reference means modifying the property's value in one method and reflecting those changes in another method. However, properties are not passed by reference by default. There are multiple ways to achieve this behavior.
Return value
One way is to return the value from the getter method and update the property in the calling method.
<code class="language-csharp">public string GetString(string input, string output) { if (!string.IsNullOrEmpty(input)) { return input; } return output; } public void Main() { Person person = new Person(); person.Name = GetString("test", person.Name); Debug.Assert(person.Name == "test"); }</code>
Delegation
Another approach is to use a delegate that takes an action that sets the property.
<code class="language-csharp">public void GetString(string input, Action<string> setOutput) { if (!string.IsNullOrEmpty(input)) { setOutput(input); } } public void Main() { Person person = new Person(); GetString("test", value => person.Name = value); Debug.Assert(person.Name == "test"); }</code>
LINQ expression
Properties can also be updated via reflection using LINQ expressions.
<code class="language-csharp">public void GetString<T>(string input, T target, Expression<Func<T, string>> outExpr) { if (!string.IsNullOrEmpty(input)) { MemberExpression expr = (MemberExpression)outExpr.Body; PropertyInfo prop = (PropertyInfo)expr.Member; prop.SetValue(target, input, null); } } public void Main() { Person person = new Person(); GetString("test", person, x => x.Name); Debug.Assert(person.Name == "test"); }</code>
Reflection
Finally, you can use reflection to set the value of a property directly.
<code class="language-csharp">public void GetString(string input, object target, string propertyName) { if (!string.IsNullOrEmpty(input)) { PropertyInfo prop = target.GetType().GetProperty(propertyName); prop.SetValue(target, input); } } public void Main() { Person person = new Person(); GetString("test", person, nameof(person.Name)); Debug.Assert(person.Name == "test"); }</code>
The above is the detailed content of How Can I Pass Properties by Reference in C#?. For more information, please follow other related articles on the PHP Chinese website!