1

I'm trying to compile following code :

internal volatile bool isRunning { get; set; }    

But the compilation fails with error message like: "the volatile modifier is not valid for that element". But the following code will be compiled fine:

internal volatile bool _isRunning;

internal bool isRunning{
    get { return _isRunning; }
    set { _isRunning = value; }
}

What is the difference between both code snippets??

2 Answers2

6

volatile (C# Reference)

The volatile keyword can only be applied to fields of a class or struct. Local variables cannot be declared volatile.

I case of Auto-implemented property or a property, compiler creates a private backing field that can be accessed through get/set. A field can be marked as volatile, but in case of of Auto implemented property, you don't explicitly define a field and thus can't mark it as volatile. That is why your first code (internal volatile bool isRunning { get; set; }) snippet doesn't compile.

In case of second code snippet

internal volatile bool _isRunning;

internal bool isRunning{
    get { return _isRunning; }
    set { _isRunning = value; }
}

You are encapsulating _isRunning field through your property isRunning. The field _isRunning can be marked as volatile.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • 2
    Yeah. So the difference is: The first version is not Csharp - at least not for any compiler. – TomTom Oct 24 '14 at 13:17
  • 1
    @TomTom, that is true. This isn't allowed even in C# 6.0. and It shouldn't be. A property itself is nothing more than syntactic sugar for get/set methods. `volatile` can only be a field. – Habib Oct 24 '14 at 13:24
0

A property with getters and setters actually compiles into methods in C#.

internal volatile bool isRunning { get; }

Would be like having

internal volatile bool getIsRunning()
{
    // Do something
}

The method isn't actually storing anything whereas the private member is.

DVK
  • 2,726
  • 1
  • 17
  • 20