I recently wrote the following statement by accident.
MyCollection myCollection = new MyCollection();
SomeMethod(myCollection.SomeVoidOperation());
Stupidly it took me some time to work out why it didn't work (Had a brainfart) but then it got me thinking; why is such a statement actually invalid in any general C type syntax context?
I understand that I can accomplish the same functionality with method chaining but what I don't get is why such a feature isn't (or perhaps can't) be implemented? To me the intent seems clear and I've tried but I can't see any ambiguity it might create. I'm sure there are some good reasons (or something that I'm missing) and hopefully someone can point it out to me.
So, why can’t an operation be performed as part of an assignment?
UPDATE:
I understand why this doesn't work. IE: I have a method that expects some parameter and I am calling a method that doesn't return anything - but you are missing my point.... I see that code as two statements one is myCollection (IE: An instance) and the second is "invoke this method".
Here is a more complete example:
public class Stock
{
public Guid ID { get; set; }
public string Description { get; set; }
}
public class StockList : List<Stock>
{
public void SomeSortOperation() { }
}
public void SomeMethod(StockList stockList)
{
}
StockList myList = new StockList();
SomeMethod(myList.SomeSortOperation());
It looks like you're trying to use the result of SomeVoidOperation
as a method argument (presumably to a method with no arguments) - but presumably you're not, because it's a void method.
It's never a good idea for code to look like it's doing one thing, when it's actually doing another.
EDIT: Okay, no, having seen the edit, I still don't think this is a good idea. You're basically saying that if you try to use a void expression as a method argument, it should actually use some different value, based on the expression. That expression would have to be very carefully defined... for example, would:
Foo(x.MethodReturningBar().MethodReturningVoid());
consider the argument to be the type of x
, or Bar
(the return type of the intermediate method call)?
Again, you're writing code which looks like it's doing one thing (using the value of the whole expression as an argument) when it's actually doing something else (using the value of part of the expression as an argument). That's simply a bad idea.