Error with embedded statements - c#

This is my code:
if (RdoBtnBeepDefault.Checked) SystemSounds.Beep.Play();
else SoundPlayer iPlay = new SoundPlayer(#TxtBeepFile.Text);
iPlay.Play();
And here's the error:
Embedded statement cannot be a declaration or labeled statement
If that isn't possible, mind telling me how?

iPlay.Play(); is beyond the scope of your else clause in your if-else statement. Try enclosing it with braces for multiple line scope.
if (RdoBtnBeepDefault.Checked)
{
SystemSounds.Beep.Play();
)
else
{
SoundPlayer iPlay = new SoundPlayer(TxtBeepFile.Text);
iPlay.Play();
)

Not only that even this can produce the same error
if (RdoBtnBeepDefault.Checked) SystemSounds.Beep.Play();
else int i=0;
The reason is logic. If you put a single line statement in if else condition which indirectly means the conditional flow is ending with that line. In that case if you use some declaration||something as above which won't make sense/impact in any way, then that means It is kind of string literal. It is not exactly wrong, rather it is unneccessary. Mind c# visual studio editor reduces almost all the possible errors and unneccessary memory loading.
When you put braces, it indiactes that you may use that variable within the same block for some logic. So the editor will allow you to do that. At that time the VS assumes you may add the code in future. So it will give you only warning about that line. Without braces it is solidly assuming that you are not going to use that variable(due to scope).So, it takes that as error.

Related

How does this seemingly unconnected block (after an if statement) work?

I've inherited some code that makes occasional use of the following if notation:
if (a)
foo();
{
if (b)
boo();
moo();
}
I'm not sure how to read that naturally but the code compiles and runs.
Can someone please explain how this works so that I can rewrite it in more human readable format? Alternatively, could someone explain why this notation could be useful?
The code you've posted would be better written as:
if (a)
{
foo();
}
if (b)
{
boo();
}
moo();
Braces in C# have two purposes:
They create a scope for variable declarations.
They group statements together so that conditionals and loops and such can apply to several statements at a time.
Whoever wrote the code you've posted chose not to use them for the second purpose. if statements can be totally legitimate without using any braces, but they'll only apply to the statement that immediately follows them (like the call to foo() after the first if).
Because there is a legitimate use case for braces that has nothing to do with control flow, however, it is perfectly acceptable for someone to put braces in random places that have nothing to do with the if statements.
This code:
foo();
{
var a = boo();
}
{
var a = moo();
}
... is equivalent to this code:
foo();
var a = boo();
var b = moo();
... but you'll notice that I couldn't name the second variable a because it's no longer separated from the first variable by scoping braces.
Alternatively, could someone explain why this notation could be useful?
There are three possibilities I can think of:
They wanted to reuse variable names in different parts of the method, so they created a new variable scope with the braces.
They thought braces might be a nice visual aid to encapsulate all the logic that's found inside them.
They were actually confused, and the program doesn't work the way they think it does.
The first two possibilities assume they're actually doing more than calling foo() and moo() in the real production code.
In any case, I don't think any of these possibilities are good reasons to write code like this, and you are totally within your rights to want to rewrite the code in a way that's easier to understand.
The curly brace starts after foo() instead of if(a) (like if(a){) therefore these braces are useless in this context.
if (a)
foo();
//{
if (b)
boo();
moo();
//}
which is equal to
if (a)
foo();
if (b)
boo();
moo();
Braces like those are used to limit context. Variables created inside these braces will exist only until the brace ends.

C# curly brackets within method body [duplicate]

I ran across a piece of C# code today I had not seen before. The programmer defined a block of code using only curly braces (no if, class, function, etc).
{
int i = 0;
}
i++; //compile error
Is there a purpose to this other than making the code look more organized? Is it good, bad, or whatever practice to use this "floating" contexts?
You can use an open and close set of curly braces to define a self containing block, which has its own scope.
This is generally not considered good programming practice, though.
Usually if someone is doing something like this, it's probably better to create a method/function in its place.
Any variable inside the "scope" of these curly braces will be out of scope outside of it.
It limits the scope of the variable to within that block. So the variable i would not be able to be seen outside of those braces.
It can also be a preference on if someone wants to separate code but using this when not necessary would in most cases be superfluous.
The braces {} in C# define scope. Anything defined within them goes "out of scope" once the braces are terminated.
The example seems kind of pointless. I can't imagine why it would be used in real world code. I'm assuming you pared down the code presented?
There is no purpose to that code at all. Probably an artifact from something else he/she was trying to do. As the comment shows this won't even compile because i is out of scope.
From a coding style perspective I personally don't like it and I've never seen someone use floating braces to "organize" their code before.
The purpose of this is to illustrate that the int i is actually in a different scope than the incremented i below it.

optional nesting? What is this language feature called, and is it intended?

I came across something interesting that I can't seem to find any more information on, or a proper name for.
I think most of us are aware that if you have multiple using blocks, you only need to include brackets after the last using:
using (FileStream fileStream = new FileStream(zipFilePath, FileMode.Open))
using (ZipInputStream zipStream = new ZipInputStream(fileStream))
{
//stuff
}
However, goofing around I found that the following code also works, without brackets immediately following the using, piggybacking the while:
using (BinaryWriter br = new BinaryWriter(context.Response.OutputStream))
while (true)
{
//stuff
}
Does anyone know the name of this language "feature" that allows code block merging?
Yes, this is intended. It is an idiom that C♯ inherits from C and C++. If you have a single statement enclosed in curly braces the braces are usually optional. Whether you use them or not is mostly an issue of style and readability. For nested using statements it's common to omit the braces for the outer layers.
Language grammar
In grammatical terms, a using block is followed by a statement. Usually this is a block statement, but it doesn't have to be.
There are a variety of kinds of statements. There are expression statements like a = b;. There are iteration statements like while (boolean-expression) { ... }. Here the entire while loop counts as a single statement. And there are block statements, which consist of one or more statements enclosed in curly braces.
See the C# Language Specification, Appendix C. Grammar, §C.2.5 Statements for a formal specification of statements:
statement:
labeled-statement
declaration-statement
embedded-statement
embedded-statement:
block
empty-statement
expression-statement
selection-statement
iteration-statement
jump-statement
try-statement
checked-statement
unchecked-statement
lock-statement
using-statement
block:
{ statement-listopt }
Usually the curly braces around statements can be omitted if you have a single statement. These are equivalent:
if (condition) statement;
if (condition) { statement; }
As are these:
using (...)
using (...)
statement;
using (...)
using (...)
{
statement;
}
using (...)
{
using (...)
{
statement;
}
}
Sometimes required
There are exceptions where curly braces are required. Method bodies must always have curly braces. It is baked into the grammar.
method-body:
block
;
Similarly, try/catch/finally clauses must have curly braces. Same thing for checked and unchecked. You can see this in the grammar. A catch clause is defined as "catch block" rather than "catch statement".
try-statement:
try block catch-clauses
try block finally-clause
try block catch-clauses finally-clause
specific-catch-clause:
catch ( class-type identifieropt ) block
general-catch-clause:
catch block
finally-clause:
finally block
checked-statement:
checked block
unchecked-statement:
unchecked block
Why is this? The short answer is it eliminates ambiguities in the grammar. For an in-depth explanation, see Eric Lippert's explanation of this inconsistency.
{ } creates a single block of code. If you do not have them, then the next statement is the block that gets executed. As such, what you are doing makes sense, since the using would apply to the while.
As described by Eric Lippert whenever you have an if/else/for/while/using/foreach/do/case/switch/ etc. expression, it is always followed by a single statement. Using braces ({ }) is just a way of making everything inside of those braces one statement. Anytime you naturally have just one statement there is rarely a need (outside of possible readability) to use the braces. Now, the readability can be reason enough in most cases, but from the compiler's point of view, it just expects any valid statement.
Using is followed by a statement, a block is a statement. Thus, although usually you have a block after using, you can have a single statement, which is while in your example but then, while is followed bya block.
Nothing unusual.
Seems to me like this "concept" is the same principle as what allows for the following:
if(somethingTrue)
when(somethingTrue)
if(somethingTrue)
// some code to be executed
Ie, a single line "block" instead of several lines within brackets.
you only need to include brackets after the last using
There is no requirement that the last using have { }. Your example is just a special case of the more general ability to nest statements with or without using compound blocks { }.
The behavior is that of the curly bracket operator. It creates a variable scope, among other uses. They can be omitted, and the code block is simply the following line.
for(int i = 0; i < 10; i++)
foreach(blah in y)
dosomething();
That's a feature of many c-like languages.

Why does C# allow {} code blocks without a preceding statement?

Why does C# allow code blocks without a preceding statement (e.g. if, else, for, while)?
void Main()
{
{ // any sense in this?
Console.Write("foo");
}
}
The { ... } has at least the side-effect of introducing a new scope for local variables.
I tend to use them in switch statements to provide a different scope for each case and in this way allowing me to define local variable with the same name at closest possible location of their use and to also denote that they are only valid at the case level.
In the context you give, there is no significance. Writing a constant string to the console is going to work the same way anywhere in program flow.1
Instead, you typically use them to restrict the scope of some local variables. This is further elaborated here and here. Look at João Angelo’s answer and Chris Wallis’s answer for brief examples. I believe the same applies to some other languages with C-style syntax as well, not that they’d be relevant to this question though.
1 Unless, of course, you decide to try to be funny and create your own Console class, with a Write() method that does something entirely unexpected.
It is not so much a feature of C# than it is a logical side-effect of many C syntax languages that use braces to define scope.
In your example the braces have no effect at all, but in the following code they define the scope, and therefore the visibility, of a variable:
This is allowed as i falls out of scope in the first block and is defined again in the next:
{
{
int i = 0;
}
{
int i = 0;
}
}
This is not allowed as i has fallen out of scope and is no longer visible in the outer scope:
{
{
int i = 0;
}
i = 1;
}
And so on and so on.
I consider {} as a statement that can contain several statements.
Consider an if statement that exists out of a boolean expression followed by one statement.
This would work:
if (true) Console.Write("FooBar");
This would work as well:
if (true)
{
Console.Write("Foo");
Console.Write("Bar");
}
If I'm not mistaken this is called a block statement.
Since {} can contain other statements it can also contain other {}.
The scope of a variable is defined by it's parent {} (block statement).
The point that I'm trying to make is that {} is just a statement, so it doesn't require an if or whatever...
The general rule in C-syntax languages is "anything between { } should be treated as a single statement, and it can go wherever a single statement could":
After an if.
After a for, while or do.
Anywhere in code.
For all intents and purposes, it's as the language grammar included this:
<statement> :== <definition of valid statement> | "{" <statement-list> "}"
<statement-list> :== <statement> | <statement-list> <statement>
That is, "a statement can be composed of (various things) or of an opening brace, followed by a statement list (which may include one or more statements), followed by a closed brace". I.E. "a { } block can replace any statement, anywhere". Including in the middle of code.
Not allowing a { } block anywhere a single statement can go would actually have made the language definition more complex.
Because C++ (and java) allowed code blocks without a preceding statement.
C++ allowed them because C did.
You could say it all comes down to the fact that USA programme language (C based) design won rather than European programme language (Modula-2 based) design.
(Control statements act on a single statement, statements can be groups to create new statements)
// if (a == b)
// if (a != b)
{
// do something
}
1Because...Its Maintain the Scope Area of the
statement.. or Function, This is really useful for mane the large code..
{
{
// Here this 'i' is we can use for this scope only and out side of this scope we can't get this 'i' variable.
int i = 0;
}
{
int i = 0;
}
}
You asked "why" C# allows code blocks without preceeding statements. The question "why" could also be interpreted as "what would be possible benefits of this construct?"
Personally, I use statement-less code blocks in C# where readability is greatly improved for other developers, while keeping in mind that the code block limits the scope of local variables. For example, consider the following code snippet, which is a lot easier to read thanks to the additional code blocks:
OrgUnit world = new OrgUnit() { Name = "World" };
{
OrgUnit europe = new OrgUnit() { Name = "Europe" };
world.SubUnits.Add(europe);
{
OrgUnit germany = new OrgUnit() { Name = "Germany" };
europe.SubUnits.Add(germany);
//...etc.
}
}
//...commit structure to DB here
I'm aware that this could be solved more elegantly by using methods for each structure level. But then again, keep in mind that things like sample data seeders usually need to be quick.
So even though the code above is executed linearly, the code structure represents the "real-world" structure of the objects, thus making it easier for other developers to understand, maintain and extend.

Why does Try-Catch require curly braces

Just curious: Why is the syntax for try catch in C# (Java also?) hard coded for multiple statements? Why doesn't the language allow:
int i;
string s = DateTime.Now.Seconds % 2 == 1 ? "1" : "not 1";
try
i = int.Parse(s);
catch
i = 0;
The example is for trivial purposes only. I know there's int.TryParse.
Consider the fact that there are really three (or more) code blocks in play here:
try {}
catch (myexcption)
{}
catch (myotherexception)
{}
finally
{}
Keep in mind that these are in the scope of a larger context and the exceptions not caught are potentually caught further up the stack.
Note that this is basically the same thing as a class construct that also has the {} structure.
Say for instance you might have:
try
try
if (iAmnotsane)
beatMe(please);
catch (Exception myexception)
catch (myotherexception)
logerror("howdy")
finally
NOW does that second catch belong to the first or the second try? What about the finally? SO you see the optional/multiple portions make the requirement.
UPDATE: This question was the subject of my blog on December 4th, 2012. There are a number of insightful comments on the blog that you might also be interested in. Thanks for the great question!
As others have noted, the proposed feature introduces ambiguities that are confusing. I was interested to see if there were any other justifications for the decision to not support the feature, so I checked the language design notes archive.
I see nothing in the language design notes archive that justifies this decision. As far as I know, C# does it that way because that's how other languages with similar syntax do it, and they do it that way because of the ambiguity problem.
I did learn something interesting though. In the initial design of C# there was no try-catch-finally! If you wanted a try with a catch and a finally then you had to write:
try
{
try
{
XYZ();
}
catch(whatever)
{
DEF();
}
}
finally
{
ABC();
}
which, not surprisingly, is exactly how the compiler analyzes try-catch-finally; it just breaks it up into try-catch inside try-finally upon initial analysis and pretends that's what you said in the first place.
More or less, this is a play on the dangling else problem.
For example,
if( blah )
if ( more blah )
// do some blah
else
// no blah I suppose
Without curly braces, the else is ambiguous because you don't know if it's associated with the first or second if statement. So you have to fallback on a compiler convention (e.g. in Pascal or C, the compiler assumes the dangling else is associated with the closest if statement) to resolve the ambiguity, or fail the compile entirely if you don't want to allow such ambiguity in the first place.
Similarly,
try
try
// some code that throws!
catch(some blah)
// which try block are we catching???
catch(more blah )
// not so sure...
finally
// totally unclear what try this is associated with.
You could solve it with a convention, where catch blocks are always associated with the closest try, but I find this solution generally allows programmers to write code that is potentially dangerous. For example, in C, this:
if( blah )
if( more blah )
x = blah;
else
x = blahblah;
...is how the compiler would interpret this if/if/else block. However, it's also perfectly legitimate to screw up your indenting and write:
if( blah )
if( more blah )
x = blah;
else
x = blahblah;
...which now makes it appear like the else is associated with the outer if statement, when in fact it is associated with the inner if statement due to C conventions. So I think requiring the braces goes a long way towards resolving ambiguity and preventing a rather sneaky bug (these sorts of issues can be trivial to miss, even during code inspection). Languages like python don't have this issue since indentation and whitespace matter.
If you assume that the designers of C# simply choose to use the same syntax as C++ then the question becomes why are braces necessary with single statements try and catch blocks in C++. The simple answer is that Bjarne Stroustrup thought the syntax was easier to explain.
In The Design and Evolution of C++ Stroustrup writes:
"The try keyword is completely redundant and so are the { } braces except where multiple statements are actually used in a try-block or a handler."
He goes on to give an example where the try keyword and { } are not needed. He then writes:
"However, I found this so difficult to explain that the redundancy was introduced to save support staff from confused users."
Reference:
Stroustrup, Bjarne (1994). The Design and Evolution of C++. Addison-Wesley.
The first think I can think of is that the curly braces create a block with its own variable scope.
Look at the following code
try
{
int foo = 2;
}
catch (Exception)
{
Console.WriteLine(foo); // The name 'foo' does not exist in the current context
}
foo is not accessible in the catch block due to the variable scoping. I think this makes it easier to reason about whether an variable has been initialized before use or not.
Compare with this code
int foo;
try
{
foo = 2;
}
catch (Exception)
{
Console.WriteLine(foo); // Use of unassigned local variable 'foo'
}
here you can not guarantee that foo is initialized.
try // 1
try // 2
something();
catch { // A
}
catch { // B
}
catch { // C
}
does B catches try 1 or 2?
I don't think you can resolve this unambiguously, since the snippet might mean:
try // 1
{
try // 2
something();
catch { // A
}
}
catch { // B
}
catch { // C
}
try // 1
{
try // 2
something();
catch { // A
}
catch { // B
}
}
catch { // C
}
Probably to discourage overuse. A try-catch block is big and ugly, and you're going to notice when you're using it. This mirrors the effect that a catch has on your application's performance - catching an exception is extremely slow compared to a simple boolean test.
In general you should avoid errors, not handle them. In the example you give, a much more efficient method would be to use
if(!int.TryParse(s, out i))
i=0;
The rational is that it's more maintainable (easier to change, less likely to break, ergo higher quality):
it's clearer, and
it's easier to change because if you need to add a line to your blocks you don't introduce a bug.
As to why exception handling is different than conditional expressions...
If/Else is conditional upon an expression to use one of two (or more If/Else if/Else) paths in the code
Try/Catch is part of exception handling, it is not a conditional expression. Try/Catch/Finally operates only when an exception has been thrown inside the scope of the Try block.
Exception handling will traverse up the stack/scope until it finds a Catch block that will catch the type of exception that was thrown. Forcing scope identifiers makes this check for blocks simplified. Forcing you to scope when dealing with exceptions seems like a good idea, it also is a good indication that this is part of exception handling rather than normal code. Exceptions are exceptions, not something you really want happening normally but know can happen and want to handle when they do happen.
EDIT: There is one more reason which I can think of, is that CATCH is mandatory after a TRY unlike ELSE. Hence there needs to be definite way to define the TRY block.
Another way of looking at this…
Given all the maintenance problem that have been created by “if”, “while”, “for” and “foreach” statements without bases, a lot of companies have coding standards that always require bases on statements that act on a “block”.
So they make you write:
if (itIsSo)
{
ASingleLineOfCode();
}
Rather then:
if (itIsSo)
ASingleLineOfCode();
(Note as indenting is not checked by the compiler, it can't be depended on to be right)
A good case could be made for designing a language that always require the bases, but then too many people would have hated C# due to having to always use the bases. However for try/catch there was not an expectation of being able to get away without using the bases, so it was possible to require them without to many people complaining.
Given a choose I would much rather have if/endIf (and while/endWhile) as the block delimiters but the USA got its way on that one. (C got to define what most languages look like rather than Module2, afterall most of what we do is defined by history not logic)
The simplest (I think) answer is that each block of code in C/C++/C# requires curly braces.
EDIT #1
In response to negative votes, directly from MSDN:
try-catch (C# Reference)
The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions.
As per definition says, it is a block, so it requires curly braces. That is why we cannot use it without { }.

Categories