Bug : dotnet CLI Template Engine Produces Invalid Code if Name of the Directory is a Valid C# Keyword

With the release of .NET Core 1.0 tooling, dotnet new make use of the templating engine to generate various types of projects like Console App, Web App, WebAPI etc. If you are not aware of it, please read my earlier post on it here.

For example, to create a new console application we only need to execute the following command

e:\test\new\dotnet new console

When this command is executed it will create two files, one with csproj extension and the second one with cs extension for you

new.csproj
program.cs

The contents of the program.cs file will be

using System;

namespace new
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
 

If you compile this using the dotnet build command, the operation will fail and will get the following errors

Program.cs(3,11): error CS1001: Identifier expected [E:\test\new\new.csproj]
Program.cs(3,11): error CS1514: { expected [E:\test\new\new.csproj]
Program.cs(3,11): error CS0116: A namespace cannot directly contain members such as fields or methods [E:\test\new\new.csproj]
Program.cs(4,1): error CS1022: Type or namespace definition, or end-of-file expected [E:\test\new\new.csproj]
Build FAILED.

Issue

So why did this happen? If you go through the code that was generated by the templating engine closely, you can see that the namespace is called new. It is a C# keyword and cannot be used to define a namespace.

So you may now be thinking that why does the templating engine used that while generating the code. It's because we didn't specify a name for the project while creating it using the dotnet new command. So the templating engine took the name of the current directory for that and we ended up with a project file called new.csproj and used the same name for defining namespace too.

This issue has been reported to Microsoft and is still in Open State. You can track the progress of it in GitHub where the repository is hosted.

"dotnet new" can generate invalid code if directory name is not a valid C# namespace identifier

Workaround

So for the time being, you can get rid of this error by specifying a name for project while using the dotnet new command as shown below

dotnet new -n TestProj console

Categories: DotNet CLI, Web Developement, MVC


No Comments

Post Reply