Home > other >  How to fix this "Invalid expression" term and syntax error in C#
How to fix this "Invalid expression" term and syntax error in C#

Time:07-12

I have an error in the code below please the best solution.

I'm using visual studio 2012

Errors are as follows:

Invalid expression term '.'

Syntax error, ':' expected

Thanks

public event JobCreatedHandler OnJobCreated;

private void DocPrinter(SafePrinter printer, string documentName, string dataType, Stream stream, bool paused, int pagecount, string printerName)
{
    var di1 = new DOC_INFO_1
            {
                pDataType = dataType,
                pDocName = documentName,
            };

    var id = printer.StartDocPrinter(di1);

    if (paused)
    {
        NativeMethods.SetJob(printer.DangerousGetHandle(), id, 0, IntPtr.Zero, (int) JobControl.Pause);
    }

    // this line throws "Invalid expression term '.'" and "Syntax error"
    OnJobCreated?.Invoke(this, new JobCreatedEventArgs {Id = id, PrinterName = printerName}); 

    try
    {
        PagePrinter(printer, stream, pagecount);
    }
    finally
    {
        printer.EndDocPrinter();
    }
}

CodePudding user response:

This is a bit of a guess because you haven't provided enough code but I think you might be mixing up the JobCreated event and the OnJobCreated method. If you are using the usual convention for events then OnJobCreated should be a method, so having a ?. after it makes no sense. In that OnJobCreated method you would raise the JobCreated event by doing JobCreated?.Invoke. Basically, you should have this:

public event EventHandler<JobCreatedEventArgs> JobCreated;

protected virtual void OnJobCreated(JobCreatedEventArgs e)
{
    JobCreated?.Invoke(this, e);
}

and then that offending line of code becomes this:

OnJobCreated(new JobCreatedEventArgs {Id = id, PrinterName = printerName});

CodePudding user response:

The "?." (null-conditional operator) syntax is available in C# 6 and higher. Visual Studio 2012 supports C# 5 only (at least out-of-the-box, see below).

You might replace the syntax by an if statement:

if (OnJobCreated != null) 
    OnJobCreated(this, new JobCreatedEventArgs {Id = id, PrinterName = printerName});

Or use a newer Visual Studio version.

Note: I never did it, but it seems to be possible to add C#6 support to VS2012: C# 6.0 Support in Visual Studio 2012.

  •  Tags:  
  • c#
  • Related