justiceorjustus justiceorjustus - 1 month ago 8
C# Question

Calling one overloaded method from another to build ViewModel C#/ ASP.NET MVC

Semi-new to ASP.NET MVC and programming in general. I have a method which builds a ViewModel that I use in most of my other Views and has two overloads. I wanted to call the first overload from the second overload to be more efficient, so I did this:

public HeaderViewModel BuildHeaderViewModel(int? chainId, int? sheetId)
{
HeaderViewModel header = new HeaderViewModel();

header.ChainName = db.Chains.Find(chainId).Name;
header.SheetName = db.Sheets.Find(sheetId).Name;
header.SheetDescription = db.Sheets.Find(sheetId).Description;

return header;
}

public HeaderViewModel BuildHeaderViewModel(int? chainId, int? sheetId, int? fileId)
{
HeaderViewModel header = new HeaderViewModel();

header = BuildHeaderViewModel(chainId, sheetId); // calling first overload

var fileDetails = db.FileDetails.Find(fileId);
header.SheetFileName = fileDetails.Name + fileDetails.Extension;

return header;
}


My question is, is this the correct / most efficient way of doing this? Any input would be appreciated.

Answer

Actually, the typical way to use chain overloads is to have the majority of the logic in the most specific one and deal with optional values appropriately:

public HeaderViewModel BuildHeaderViewModel(int? chainId, int? sheetId)
{
    return BuildHeaderViewModel(chainId, sheetId, null);
}

public HeaderViewModel BuildHeaderViewModel(int? chainId, int? sheetId, int? fileId)
{
    HeaderViewModel header = new HeaderViewModel();

    header.ChainName = db.Chains.Find(chainId).Name;
    header.SheetName = db.Sheets.Find(sheetId).Name;
    header.SheetDescription = db.Sheets.Find(sheetId).Description;

    if(fileId.HasValue)
    {
        var fileDetails = db.FileDetails.Find(fileId);
        header.SheetFileName = fileDetails.Name + fileDetails.Extension;
    }
    return header;
}

The main difference is that your current method does nothing different if fileId is null, which may be OK, in which case you can take the null check out of the overload.