c# - dereference * versus multiplication * ambiguity -
in last line of main(), error trying pointer stuff, i'm trying invoke multiplication operator defined inside foo class. if isn't syntax invoking multiplication, is?
namespace test { class program { class foo { int foo; public foo(int n) { foo = n; } public static object operator *(foo a,foo b) { return new foo(a.foo * b.foo); } } static void main(string[] args) { foo = new foo(2); foo b = new foo(3); * b; } } } i'm sure it's stupid, don't see it.
in c#, expressions can used statements (i.e. expressions can evaluate , ignore result of evaluation) are:
- assignments:
a = b;- the obvious valid statement, assignment expression has result value, means can write one-liners
if ((a = b) == c) dostuff();- still "not using" result of assignment expression when doing plain assignment
- the obvious valid statement, assignment expression has result value, means can write one-liners
- method calls:
dostuff();- even if
dostuffreturns value, can use statement - if call
a.tostring();without storingstringanywhere, compiler won't complain
- even if
- increments/decrements:
i++;,i--;- post/pre-increment result semantics pretty same in c-like languages, doesn't matter if use result (as in
var x = i++;) or not
- post/pre-increment result semantics pretty same in c-like languages, doesn't matter if use result (as in
- awaiting on method:
await doasyncstuff();- you can await on async operation without having consume result (this analogous plain method calls)
newobject expressions:new foo();- even if don't assign newly instantiated object anything, constructor might number of things affecting state of program, create static references (otherwise collected)
so, since not consuming result of operation (assigning variable), c# compiler assumes trying define variable b of type a*:
static void main(string[] args) { foo = new foo(2); foo b = new foo(3); // seen compiler "type* variable;" * b; } this why gives several compiler errors, like:
avariable, being used type- pointers allowed in unsafe context
if used + operator, wouldn't have mentioned pointers, have complained weren't supposed use expression statement, make more obvious.
to resolve error, assign result of expression variable:
// type of `result` object, btw var result = * b; as side note, wiser operator * method returns result of type foo, instead of plain object:
public static foo operator *(foo a, foo b) { ... } // type of `result` `foo`, should foo result = * b; final suggestion concrete example candidate immutable struct, instead of class (similar point struct, example).
Comments
Post a Comment