Home > front end >  Can't run Program.cs in VSCode if there is an error in another non-used .cs file
Can't run Program.cs in VSCode if there is an error in another non-used .cs file

Time:10-03

I've written a lot of Python (and a bit of C/C many years ago) but am now staring on C# (.NET).

I'm using VSCode as my IDE.

I have the following folder structure

test/
├─ Program.cs
├─ Car.cs

with

//Program.cs

class Progam
{
    static void Main(string[] args)
    {

        Console.Write("Hello SO!");
    }

}

and that runs fine when I press CTRL F5 (Run without debugging).

I've then moved into classes in C#, which is the Car.cs file.

I have an error (I forgot a semicolon)

//Car.cs

class Car
{
    string color = "red";
    int n_wheels = 4 // Wups, missing semicolon
}

Note, I haven't changed the Program.cs file, but now when I press CTRL F5 I get the error

C:\Users\Me\Documents\C#\test\Car.cs(8,21): error CS1002: ; expected [C:\Users\Me\Documents\C#\test\Test.csproj]

I might still quite have understood how .NET/C# compiles the stuff and runs the program, but I just wonder, why it throws an error in the Car.cs when that class isn't used at all in the Program.cs, which is the only file that contains a Main function.

I could understand if I've imported the Car file but I do not - I don't use it anywhere and it does not have a Main function.

So my question is; how do I avoid such stuff, when I have files that I'm currently developing (but am not using) that might have some bugs/issues due to it being under construction?

CodePudding user response:

Following up on the comments, and after viewing the OP's bio I can see where this question is coming from.

You are comparing python's execution path to C#'s.

In python (yes, I know python is compiled - I'm simplifying):
The interpreter is going over the commands in a sequential manner and executing them.

i.e. If you have an import within a function - the interpreter will not know or care about the import until it is required, and thus code with bad syntax in another module (= file, for C# speakers) will not affect your program.

C# works a bit differently. The first step is compiling the code and creating a binary file which will be executed.
That file is the binary representation of all the source code files referenced in your project. Hence:

  1. Any file that has syntax error will fail the project compilation
  2. The binary will not build.
  3. You will not be able to execute the binary.

This is why a syntax error in any file will not allow you to execute your code.

Another way to think about is is that in python the imports are done in run time, while in C# its in compile time.
In both cases a malformed reference file will break the process.
C# simply does it earlier.

So my question is; how do I avoid such stuff

Well, you can fix the syntax error, or comment that part out until you get to it...

  • Related