开发者

Return multiple values from a method

Hi guys i'm having a problem regarding returning multiple values from a method. I'm using 'out' to return other value from a method, here the snippet:

public DataTable ValidateUser(string use开发者_C百科rname, string password, out int result)
{
    try
    {
        //Calls the Data Layer (Base Class)
        if (objDL != null)
        {
            int intRet = 0;
            sqlDT = objDL.ValidateUser(username, password, out intRet);
        }
    }
    catch (Exception ex)
    {
        ErrorHandler.Handle(ex);
        OnRaiseErrorOccuredEvent(this, new ErrorEventArgs(ex));
    }
    return sqlDT;
}

then when i compile having a error like this:

"The out parameter 'return' must be assigned to before control leaves the current method"

Anyone guys can help me solve this.


That means in all possibilities (inside and outside the if, in the catch), your result variable must be assigned.

The best approach would be to give it a default value at the start of the function:

public DataTable ValidateUser(string username, string password, out int result)
{
    result = 0;
    try
    {
        //Calls the Data Layer (Base Class)
    if (objDL != null)
    {
        int intRet = 0;
        sqlDT = objDL.ValidateUser(username, password, out intRet);
        result = intRet;
    }
//....


The parameter result of your method is marked as out. Parameters marked with out must be assigned within your method, i.e

result = 5;

This is enforced so callers of your method have the guarantee that the parameter that is passed with out is always set once your method finishes.


You're not setting the result variable in the method.

I'm guessing you want to add an extra line such as

result = intRet;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜