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
  • method calls: dostuff();
    • even if dostuff returns value, can use statement
    • if call a.tostring(); without storing string anywhere, compiler won't complain
  • 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
  • awaiting on method: await doasyncstuff();
    • you can await on async operation without having consume result (this analogous plain method calls)
  • new object 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:

  • a variable, 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

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -