Search code examples
c#refanonymous-methods

Is it possible do not copy ref to local variable?


I'm trying declare ref object as optional parameter. So I've understood why I can't do that. The decesion was to overload my method and now I have a new problem:

public Guid GetIdByEmployeeTypeName(string typeName)
{
    return SurroundWithTryCatch(() => new EmployeeType().GetEmployerGroupIdByTypeName(typeName));
}

public Guid GetIdByEmployeeTypeName(string typeName, ref EmployeeType employeeType)
{
    EmployeeType type = employeeType; //The problem here. I can not use ref object inside an anonymous method.
    return SurroundWithTryCatch(() => type.GetEmployerGroupIdByTypeName(typeName));
}

How can I optimize my code?


Solution

  • I wouldn't say it's a good (or very bad) idea, but you can create overload without ref and call method requiring one with value which is not used to return:

    public Guid GetIdByEmployeeTypeName(string typeName)
    {
        var tmp = new EmployeeType();
        return GetIdByEmployeeType(typeName, ref tmp);
    }