1

This code compiles:

public static void SetBackLink(dynamic viewBag, NameValueCollection queryString, bool defaultToServicePage = false) {
    if (defaultToServicePage && string.IsNullOrEmpty(viewBag.BackLinkUrl)) {
        if (!long.TryParse(queryString["serviceId"], out long serviceId)) {
            return;
        }
        viewBag.BackLinkUrl = UserEntityService.CalculationService.GetServicePageUrl(serviceId);
        viewBag.BackLinkText = UserEntityService.CalculationService.GetServiceTitle(serviceId);
    }
}

This code has compiler error Use of unassigned local variable 'serviceId' on the third line:

public static void SetBackLink(dynamic viewBag, NameValueCollection queryString, bool defaultToServicePage = false) {
    if (defaultToServicePage && string.IsNullOrEmpty(viewBag.BackLinkUrl) && long.TryParse(queryString["serviceId"], out long serviceId)) {
        viewBag.BackLinkUrl = UserEntityService.CalculationService.GetServicePageUrl(serviceId);
        viewBag.BackLinkText = UserEntityService.CalculationService.GetServiceTitle(serviceId);
    }
}

I have the following version of Visual Studio:

Microsoft Visual Studio Enterprise 2019
Version 16.4.5
VisualStudio.16.Release/16.4.5+29806.167
Microsoft .NET Framework
Version 4.8.03752
Installed Version: Enterprise

Is this a compiler bug?

  • 1
    Maybe caused by the `dynamic`. If change to specific type, it has compiled. I also cannot understand why this not compile. –  Aug 15 '20 at 21:19
  • Thanks. I reported it as a compiler bug. – Tore Olav Kristiansen Aug 15 '20 at 21:27
  • 2
    This is not a compiler bug: it's a very definite consequence of how `dynamic` works. Eric Lippert ended up doing a nice write-up: [Part 1](https://ericlippert.com/2018/11/14/a-dynamic-definite-assignment-puzzle/), [Part 2](https://ericlippert.com/2018/11/19/a-dynamic-definite-assignment-puzzle-part-2/) – canton7 Aug 15 '20 at 21:39
  • FWIW, using `dynamic` usually creates 2 more problems for every problem it solves – TheGeneral Aug 15 '20 at 22:31
  • @canton7 I updated the bug report. Thanks :) – Tore Olav Kristiansen Aug 16 '20 at 00:22

0 Answers0