Why does this compile with a space: this.option1 .Checked = true;

  • Thread starter Thread starter Johann Blake
  • Start date Start date
J

Johann Blake

Is this a bug in the C# compiler when it parses code, or is there a
legitimate reason why the following code is legal. If so, explain why.

On a form, add an option button (radio button). Call it option1.

In code behind the form, simply write this line of code (make sure to
include the space after the word option1 and the dot:

this.option1 .Checked = true;

This compiles on my machine. Why? What makes using a space legitimate.

Regards,
Johann Blake
 
That is just the semantics of C#.
You may also do
this.option1





..Checked = true;

if you want.
 
Johann Blake said:
Is this a bug in the C# compiler when it parses code, or is there a
legitimate reason why the following code is legal. If so, explain why.

On a form, add an option button (radio button). Call it option1.

In code behind the form, simply write this line of code (make sure to
include the space after the word option1 and the dot:

this.option1 .Checked = true;

This compiles on my machine. Why? What makes using a space legitimate.

Here's a somewhat simpler example:

using System;

public class Test
{
string x = "hello";

public static void Main()
{
Test t = new Test();
Console.WriteLine(t.x .Length);
}
}

As for the validity - I'm not terribly hot on the details here, but the
spec does say:

<quote>
The lexical processing of a C# source file consists of reducing the
file into a sequence of tokens which becomes the input to the syntactic
analysis. Line terminators, white space, and comments can serve to
separate tokens, and pre-processing directives can cause sections of
the source file to be skipped, but otherwise these lexical elements
have no impact on the syntactic structure of a C# program.
</quote>

I guess in this the tokens here are "t" "." "x" "." and "Length". Note
that you can put them on different lines if you like, too, and even put
comments in the middle:

Console.WriteLine (t
 
Hi Johann:

I'm no expert, but here's my 2-cents' worth.

First, the short version:
No bug. Legal. My understanding is that in C# extra white space such as
space, linefeed, tab etc. is ignored. That's why you need ; to end a
statement.

Medium answer:
The . is enough to separate the object from the member. If you like, you
could even press <Enter> or <Tab>.

A bit more detail:
This gives you the freedom to format your code as you like to show
structure. This can eventually make the program easier to understand. So
it's easier firstly to get right, and secondly to revise by you when you've
forgotten how you made it or by someone else who never knew what you did.

The Microsoft IDE's source editor can help in the formatting.

Summary:
Deliberate feature to promote readability, maintainability.
 
Back
Top