Out parameter issue

I am having trouble calling the method I made.

The method I refer to is as follows:

public bool GetValue(string column, out object result)
{
    result = null;
    // values is a Dictionary<string, object>
    if (this._values.ContainsKey(column))
    {
        result = Convert.ChangeType(this._values[column], result.GetType());
        return true;
    }
    return false;
}

I am calculating a method using this code, but I get a compiler error

int age;
a.GetValue("age", out age as object) 

The argument ref or out must be an assignable variable.

Has anyone else had this problem, or am I just doing something wrong?

+5
source share
3 answers

The variable must be completely from the type specified in the method signature. You cannot use it in a call.

An expression is age as objectnot an assigned value because it is an expression, not a storage location. For example, you cannot use it on the left side of a task:

age as object = 5; // error

If you want to avoid casting, you can try using the general method:

public bool GetValue<T>(string column, out T result)
{
    result = default(T);
    // values is a Dictionary<string, object>
    if (this._values.ContainsKey(column))
    {
        result = (T)Convert.ChangeType(this._values[column], typeof(T));
        return true;
    }
    return false;
}

, ​​ )

+12

public bool GetValue<T>(string column, out T result)
{
    result = default(T);
    // values is a Dictionary<string, object>
    if (this._values.ContainsKey(column))
    {
        result = (T)Convert.ChangeType(this._values[column], typeof(T));
        return true;
    }
    return false;
}

example invoke

int age;
a.GetValue<int>("age", out age);
+2

object age; 
a.GetValue("age", out age);

int iage = (int)age;
0

All Articles