Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with out parameter

Tags:

c#

.net

I'm having problems with calling a method that I have made.

The method I'm calling to is as folows

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'm caling the method with the this code but I get an compiler error

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

A ref or out argument must be an assignable variable

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

like image 580
Bobo Avatar asked Sep 19 '12 09:09

Bobo


2 Answers

The variable needs to be exatly of the type specified in the method signature. You can't cast it in the call.

The expression age as object is not an assignable value because it is an expression, not a storage location. For example, you cannot use it on the left hand of an assignment:

age as object = 5; // error

If you want to avoid casting, you could try using a generic 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;
}

Of course, some error checking should be inserted where appropriate)

like image 153
Botz3000 Avatar answered Nov 16 '22 02:11

Botz3000


Try this

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);
like image 21
daotan Avatar answered Nov 16 '22 00:11

daotan