I really don't understand why c# compiler allows some useless statements but disallows some other useless statements.
static void Main()
{
string('a', 1); // useless but allowed
//"a";// useless and disallowed
new int(); // useless but allowed
//0;// useless and disallowed
new char(); // useless but allowed
//'\0';// useless and disallowed
new bool(); // useless but allowed
//false;// useless and disallowed
//new int[] { 1, 2 };// useless and disallowed
//new [] { 1, 2 };// useless and disallowed
//new int[2];// useless and disallowed
//new int[2].Length;// useless and disallowed
int[] var = new int[2]; // useful
//var.Length;// useless and disallowed
string s = string.Empty; // useful
//string.Empty;// useless and disallowed
}
Those are not "useless" statements. You're calling a constructor, and you don't know what the constructor might do - it may have important side-effects. It may be logging stuff, initializing a connection, etc. Even though it's a bad practice, the compiler can't force you to remove them.
As for your other statements:
0
, false
: integer and boolean literals have no side effects.arr.Length
, properties shouldn't have any side effects (although they may have).So it's safe to force the developer to remove these statements.
Method and constructor calls are allowed, because they can have side effects.
Other things don't, because they don't have side effects (or shouldn't, as in the case of properties).
These statements are not useless, you just don't store their values. But you can write for example
Console.WriteLine(new int()); // output: 0
Calling a constructor is a valid statement which creates a value, the problem is that you don't assign this value to any variable so it's not available later.
Writing a literal like 0;
as a statement is not allowed because
Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Obviously that doesn't explain why the C# compiler team didn't allow the use of literals like that but I would imagine that it is either because
The reason why new ClassName();
is allowed as a statement without storing it into a variable is that constructors can introduce side-effects which might be what the developer wanted to do. Disallowing such a construct would mean the developer had to introduce a meaningless variable for no benefit at all.
The question remains why new int();
is allowed although the use of the literal 0;
is not. Yet again I do not know the answer but possible reasons could be
new ClassName();
is allowed then new int();
should be tooIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With