0

Is there any way to create a local variable in a function, calculate it and return that function in same line,

For Example making this function

 public static List<string> CalculateScore(this IEnumerable<GatheredMissionScore> list)
    {
        var calculatedScore = list.Select(gatheredScore => gatheredScore.ToString()).ToList();
        return calculatedScore;
    }

Like This

 public static List<string> CalculateScore(this IEnumerable<GatheredMissionScore> list)
        {
            return var calculatedScore = list.Select(gatheredScore => gatheredScore.ToString()).ToList();          
        }
Akin Erkan
  • 273
  • 3
  • 14
  • What would be the use case for such operation if one to be added to the language? Some clarification of what you want to achieve/understand would help a lot in getting an answer. – Alexei Levenkov May 05 '20 at 23:54
  • you probably want `Sum` or `Aggregate` but you need to have a numerical score first and it's not clear from your example what your data structures look like. – Dave Cousineau May 05 '20 at 23:55
  • I just wanted to make it expression body if this could be in line. – Akin Erkan May 05 '20 at 23:58
  • 3
    Just return the result of the expression and make it expression-bodied. Why do you want the variable? – madreflection May 05 '20 at 23:58
  • 3
    Remove `var calculatedScore =`. Job done. – mjwills May 05 '20 at 23:59
  • Yep thats work thanks :) but is there any way to do it like I asked in c#, or its reaaly meaningless to be make it inline ? – Akin Erkan May 06 '20 at 00:04
  • 2
    What's the point of the variable if you do that? Control leaves the method immediately due to the `return` statement. You can't use the variable. This is sounding like it might be an XY problem. If you want to inspect the return value while debugging, use the Autos window. It shows the last returned value. – madreflection May 06 '20 at 00:08
  • 2
    `is there any way to do it like I asked in c#` Your first code sample is the way to do it if you want the temporary variable. My suggestion is the way to do it if you don't. – mjwills May 06 '20 at 00:09
  • I couldn't see that at first look. Thank you all for clarification. – Akin Erkan May 06 '20 at 00:11
  • Using you use a variable opinion based. You could also write it as [Expression-bodied members](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members) Use what you like, but use it consequent. – Jeroen van Langen May 06 '20 at 00:13

0 Answers0