Invalid token '=' in C # class, structure or interface member declaration

This may be a simple question for people, but I do not understand why this is happening. here is my 1st code:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameCore { public class PlayerCharacter { public void Hit(int damage) { Health -= damage; if (Health <= 0) { IsDead = true; } } public int Health { get; private set; } = 100; public bool IsDead{ get; private set; } } } 

now Visual studio is giving the wrong token error on the destination sign (=) (according to the header), and I don't understand why. can anyone shed some light on this please?

What I'm trying to do is set the health int value to 100, and every time a character takes damage, then his health decreases. Thanks to everyone.

I am using Visual Studio 2013 v12.0.40629.00 update 5

+6
source share
3 answers

The default setting for automatically implemented properties is only available from C # -version 6 and above. Before version 6, you should use the constructor and set the default value there:

 public class PlayerCharacter { public int Health { get; private set; } public PlayerCharacter() { this.Health = 100; } } 

To enable the compiler for VS2013, you can use this approach .

+9
source

The answer was:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameCore { public class PlayerCharacter { public int Health { get; private set; } public PlayerCharacter() { this.Health = 100; } public void Hit(int damage) { Health -= damage; if (Health <= 0) { IsDead = true; } } public bool IsDead{ get; private set; } } } 

makes the constructor a function with (), and not like PLayerCharacter {etc.

thanks everyone, go back to my hole, I'm leaving.

0
source

It seems this error is due to the version of your MSBuild, the old version of MSBuild can only compile C # version 4, and your code is written in C # version 6 format (set the default value for the properties).

An example of writing code in C # version 6:

  public static string HostName { get; set; } = ConfigurationManager.AppSettings["RabbitMQHostName"] ?? ""; 

For MSBuild to compile your code, you need to write in C # 4 style

 public static string HostName { get; set; } public SomeConstructor() { HostName = ConfigurationManager.AppSettings["RabbitMQHostName"] ?? "";... } 

or

  public static string HostName { get { return ConfigurationManager.AppSettings["RabbitMQHostName"] ?? ""; } } 

Hope this helps

0
source

All Articles