Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for using goto

Tags:

c#

.net

goto

Is it right to use goto in this code? Are there any alternatives?

return ExecuteReader(cmd, reader =>
{
    List<BEPartnership> partnerhip = null;

    //Partnership
    if (!((SqlDataReader) reader).HasRows)
        goto exit;

    partnerhip = 
        new List<BEPartnership>{new BEPartnership().GetFromReader(reader)};

    //Customers
    if (!reader.NextResult() && !((SqlDataReader) reader).HasRows)
        goto exit;

    foreach (BEPartnership p in partnerhip)
        p.Partner = new BECustomer().GetFromReader(reader);

    //Contracts
    if (!reader.NextResult() && !((SqlDataReader) reader).HasRows)
        goto exit;

    List<BEContractB2B> contracts = new List<BEContractB2B>();
    contracts.Add(new BEContractB2B().GetFromReader(reader));
    // contracts = new BEContractB2B().GetFromReader2(reader).ToList();

    exit:
    return partnerhip;
});
like image 701
Alexandre Avatar asked Mar 30 '11 10:03

Alexandre


2 Answers

You can replace each goto exit; with return null; or return partnerhip; if you wish to return the currently populated list. (I assume a partnerhip is a cool partner?)

like image 122
devdigital Avatar answered Sep 27 '22 20:09

devdigital


I would say no.

I've been programming in C# since 2001 and have never used goto!

If you want a "short circuit" exit in your code, why not replace the

goto exit:

with

return partnership
like image 37
Rob Levine Avatar answered Sep 27 '22 21:09

Rob Levine