6

I have this foreach section and i am trying to add a line after my "result = string.Format" but i get the following error "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement" can someone tell me what i am doing wrong.

foreach (DataRow record in table.Rows)
{
    string key = record["Code"] + "_" + record["Description"];
    int row = (int)rownum[key];

    string date = formatDate(record["ApptDate"].ToString(), "_");

    string result = string.Empty;
    if (record["Dosage"].ToString() != string.Empty)
        result = string.Format("{0}/{1}", test.SharedLib.Application.RemoveTrailingZeroes(record["Dosage"].ToString()), 
                                          test.SharedLib.Application.RemoveTrailingZeroes(record["Units"].ToString()));
    if (record["Dosage"].ToString() != string.Empty)
        result.StartsWith("/") && result.EndsWith("/") ? result.Replace("/", string.Empty) : result;
    else if (record["Units"].ToString() != string.Empty)
        result = record["Units"].ToString();

    dataTable.Rows[row]["ApptDate" + date] = result;
}
Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
Robert
  • 646
  • 4
  • 12
  • 37

4 Answers4

5
if (record["Dosage"].ToString() != string.Empty)
    result.StartsWith("/") && result.EndsWith("/") ? result.Replace("/", string.Empty) : result;

The second line there is not a statement, it is an expression. Not all expressions can be statements in C#, so this is a syntax error.

Presumably you meant to assign the result of this to result:

if (record["Dosage"].ToString() != string.Empty)
    result = (result.StartsWith("/") && result.EndsWith("/")) ? result.Replace("/", string.Empty) : result;

Further, you should consider enclosing the bodies of if / else blocks with braces ({}). Without braces, the way in which these blocks nest is not intuitive, and it will hamper future maintenance. (For example, can you tell which if block the else if block will belong to? Will the next person who inherits this project be able to not only tell the difference, but understand what nesting was intended? Make it explicit!)

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • The lack of curly braces is definitely a matter of personal preference in this case, I think. Though I agree that the code currently looks cluttered without them. Another approach might be to extract some of the longer lines into private methods with more intuitive names which describe the logic being performed. Then the code would read a lot cleaner without the need for grouping long statements with curly braces. – David Jul 23 '13 at 20:30
  • 2
    @David While I generally agree regarding personal preference, this is not one such case. Without braces code is more easily damaged under maintenance, especially *exactly* the kind of code in the question. According to the question, he inserted the middle `if` block. Did he mean for it to be part of the body of the first `if` block, and does he realize that the `else` block now belongs to the new `if` block and not the first one? Braces help to disambiguate exactly these kinds of questions. All at the cost of one extra line to contain the final `}`. This is a good trade-off. – cdhowie Jul 23 '13 at 20:32
2

You have to do something with the result of your expression (e.g. assign it to result?!)

For more information you should really format and tell us more about your code...SO users are not your personal compiler/debugger ;-)

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • Nor do I see any missing curly braces that would otherwise be required. – David Jul 23 '13 at 20:26
  • I don't see any missing braces either. The OP doesn't *need* them, but using braces in conditionals like this would be a very good thing as it's not clear at all if the way he has them nested is the way he wants them nested. – cdhowie Jul 23 '13 at 20:27
  • @D.R. The code was edited, but no semicolons were added or removed. The only edits were to whitespace. – cdhowie Jul 23 '13 at 20:28
  • Whoops, sorry for the confusion, you're right. I haven't seen the second if before the else if due to the unfortunate formatting. – D.R. Jul 23 '13 at 20:31
  • I removed the confusing part of my answer, sorry again. – D.R. Jul 23 '13 at 20:31
0
result.StartsWith("/") && result.EndsWith("/") ? result.Replace("/", string.Empty) : result;

This line does nothing with the result of the ternary operator. I assume you'd want to assign it to result

Tyler
  • 578
  • 3
  • 10
0

In my case I got the error as follows

Message=(1,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
  Source=Microsoft.CodeAnalysis.Scripting

when I called the following method.

private static async Task TrialUsingRoslynScriptingApi1()
{
    var scriptOptions = ScriptOptions.Default;

    var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // .SingleOrDefault(assembly => assembly.GetName().Name == "MyAssembly");

    foreach (Assembly assembly in assemblies)
        scriptOptions = scriptOptions.AddReferences(assembly);


    scriptOptions = scriptOptions.AddImports("System");
    scriptOptions = scriptOptions.AddImports("System.Collections.Generic");
   
    var codeString = @"iList =>
    {
        var finalResult = 0;

        foreach (var i in iList)
            finalResult = finalResult + i;

        return finalResult;
    };
    return arithmeticSum;";

    Func<List<int>, int> arithmeticSum = await CSharpScript.EvaluateAsync<Func<List<int>, int>>(codeString, scriptOptions);
        
    var iListOfNumbers = new List<int>() { 1, 2, 3, 4, 5 };

    Console.WriteLine(arithmeticSum.Invoke(iListOfNumbers));
    Console.WriteLine(arithmeticSum(iListOfNumbers));

}

To mitigate that, I changed the codeString to the following. Note the return statement in the end and the assignment in the begining.

var codeString = @"Func<List<int>, int> arithmeticSum = iList =>
    {
        var finalResult = 0;

        foreach (var i in iList)
            finalResult = finalResult + i;

        return finalResult;
    };
    return arithmeticSum;";

Note that this is not a regular use case, I am trying to compile a piece of code using roslyn(.NET Compiler platform) on the fly.

To run this example, do the following.

  1. create a console app on .net core
  2. Add Microsoft.CodeAnalysis.CSharp.Scripting nuget package.
  3. Add some or all of the following using statements as needed.

Using statements

using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
  1. Finally call the method as follows.

Main method in Program.cs file should be as follows.

static async Task Main(string[] args)
{
    Console.WriteLine("Hello World! A demo of string to lambda with Roslyn");

    await TrialUsingRoslynScriptingApi1();

}
VivekDev
  • 20,868
  • 27
  • 132
  • 202