I'm trying to do do the following:
GetString(
inputString,
ref Client.WorkPhone)
private void GetString(string inValue, ref string outValue)
{
if (!string.IsNullOrEmpty(inValue))
{
outValue = inValue;
}
}
This is giving me a compile error. I think its pretty clear what I'm trying to achieve. Basically I want GetString
to copy the contents of an input string to the WorkPhone
property of Client
.
Is it possible to pass a property by reference?
without duplicating the property
Another trick not yet mentioned is to have the class which implements a property (e.g.
Foo
of typeBar
) also define a delegatedelegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);
and implement a methodActOnFoo<TX1>(ref Bar it, ActByRef<Bar,TX1> proc, ref TX1 extraParam1)
(and possibly versions for two and three "extra parameters" as well) which will pass its internal representation ofFoo
to the supplied procedure as aref
parameter. This has a couple of big advantages over other methods of working with the property:Passing things be
ref
is an excellent pattern; too bad it's not used more.Properties cannot be passed by reference. Here are a few ways you can work around this limitation.
1. Return Value
2. Delegate
3. LINQ Expression
4. Reflection
Just a little expansion to Nathan's Linq Expression solution. Use multi generic param so that the property doesn't limited to string.
This is not possible. You could say
where
WorkPhone
is a writeablestring
property and the definition ofGetString
is changed toThis will have the same semantics that you seem to be trying for.
This isn't possible because a property is really a pair of methods in disguise. Each property makes available getters and setters that are accessible via field-like syntax. When you attempt to call
GetString
as you've proposed, what you're passing in is a value and not a variable. The value that you are passing in is that returned from the getterget_WorkPhone
.If you want to get and set the property both, you can use this in C#7: