Is there a this[] in C#

  • Thread starter Thread starter Ernst Sauer
  • Start date Start date
E

Ernst Sauer

Hello,

Forgive me, if this is a stupid question, but I'm a new C# member.
C++ hase a this[] operator but I'm missing it in C#

How would you solve a problem like the following:

class CNode
{
public double x;
….
public mid();
{ i = ???
x=(this[i-1].x + this[i+1].x)/2;
}
}

//
CNode[] node = new Cnode[10];
…
Node[5].mid();


Thanks
 
Ernst said:
Forgive me, if this is a stupid question, but I'm a new C# member.
C++ hase a this[] operator but I'm missing it in C#

C# also can overload the square bracket operator. But your code will be
in C++ as wrong as in C#.

You apply the index operator to an *item* of the Array rather than to
the Array itself. You need to write a container class rather than a node
class to provide functionality for the sequence of nodes.


Marcel
 
Am 25.03.2011 15:37, schrieb Peter Duniho:
....
I'd say that this
is a good example of why I prefer C# over C++. C++ allows a lot more
"funny business" to show up in code, because you have such direct access
to the various data structures. That often leads to code such as what
you've posted, where the intent and mechanism of the code is far from
obvious.

You are right Pete.
Also I get no error in C++ (not from the compiler and not at run-time)
with
xx=(this[i-1].x + this[i+1].x)/2.;
I do not get what I expect.
Some .x are correct others are wrong.
Perhaps one could figure out the correct i, but that is nonsense.

Ernst
 
Hi,

Ernst said:
Also I get no error in C++ (not from the compiler and not at run-time)
with
xx=(this[i-1].x + this[i+1].x)/2.;

it is undefined behavior in C++. You must not access any object except
for *this and its components via the this pointer. So please delete the
wrong code. You will not get it working with this object design. Neither
in C++ nor in C#, where the compiler told you that you made something
wrong, nor in any other OO language.
It is like you query a car about the colors of the cars before and after
it, but it only knows it's own color. Then it looks 5 meters behind, and
if there happens to be another car, it will tell the right color, but if
not it will tell you the color of the street.


Marcel
 
Back
Top