I'm trying to do
myDic.TryGetValue("username", out user.Username);
but its not working.
is this not possible?
I'm trying to do
myDic.TryGetValue("username", out user.Username);
but its not working.
is this not possible?
No, from the documentation:
"Properties are not variables and therefore cannot be passed as out parameters."
To continue John's answer, do this instead:
string username;
if (myDic.TryGetValue("username", out username))
{
user.Username = username;
}
You could do this in VB, but not C#.
VB will generate a temporary variable (on the stack), pass in it's address to the out value, and then do an assignment to the property after the method call.
Generally VB does this because it does lots of implicit stuff all over the place. That's just the way it works.
C#, on the other hand, tends to eschew implicitness as part of its philosophy. That's why, for example, you have to add "out" to the call site in order to get out parameters to work, and why it doesn't support "ref" parameters for the first argument to extension methods.
It would be possible to support properties here, using an explicit "out" syntax at the call site. However, I believe the reason they don't do this is because the trick VB uses does not behave exactly the same for properties as it does for fields. With a field, the assignment would take place immediately where it occurred inside the method. If there was other code in the method that read the field (by calling a method on the object), it would read the new field value assigned via the output parameter.
With properties, using the VB trick, the property doesn't get assigned until after the method returns. This means that any code that read the property directly after the out parameter assignment would read the old value.
Here's a simple example of what I mean:
class C
{
private int m_bar;
public int Bar { get { return m_bar; } set { m_bar = value; }}
void foo(out int x)
{
x = 2;
Console.WriteLine(Bar);
}
void DoStuff()
{
foo(out m_bar); //outputs 2
Bar = 0;
//pretend this works
foo(out Bar); //outputs 0
Console.WriteLine(Bar); // outputs 2
}
}
Inside DoStuff(), you would get different behavior for the first call to foo than you would from the second call to foo, although most folks would expect them to behave the same way.
Generally C# tries to avoid these types of things.
That's my guess as to why they don't support it (the spec just says that don't support, it doesn't really say why).