Home > Software engineering >  Cannot implicitly convert type <anonymous type>
Cannot implicitly convert type <anonymous type>

Time:08-22

I have implemented the following iterator-method:

private IEnumerable<(string Department, TimeSpan From, TimeSpan To)> ParseConfig() {
    var lines = this.config.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
    foreach (var line in lines) {
        var values = line.Split(';');
        if(values.Length < 3) {
            continue;
        }
        yield return new { Department = values[0], From = TimeSpan.Parse(values[1]), To = TimeSpan.Parse(values[2]) };
    }
}

at the return statement I get the error

Cannot implicitly convert type '<anonymous type: string Department, System.TimeSpan From, System.TimeSpan To>' to '(string Department, System.TimeSpan From, System.TimeSpan To)'

Can someone help me, why do this happen?

CodePudding user response:

You return an anonymous type but the method wants to return a named tuple:

yield return ( values[0], TimeSpan.Parse(values[1]), TimeSpan.Parse(values[2]) );

You don't need to specify the names again here for named tuples, because the compiler can resolve them already from the method signature.

  • Related