Incorrect height with sampleHeight

The case is: I have cube which I want to move along a non-flat terrain just by setting the cube.position.y = the height of terrain below the cube. All this with C#.

I was adviced to use sampleHeight but after trying dozens of different forms and even javascript the height was never correct.

By the way even the "Terrain.SampleHeight" example (as C#) in Unity API gives an error BUT I managed to get it working (but with incorrect height) like this:

height = Terrain.activeTerrain.SampleHeight(cube.position);
cube.position = new Vector3(cube.position.x, height, cube.position.z);

With this piece of code, during the game if I move the cube around the terrain, it's always 22 units too high on y axis. Of course I could just add -22 to the height but why it's incorrect in the first place? Is there something wrong with the code because I had to find it out myself?

There is nothing wrong with SampleHeight. If you read the docs, it says the value is in terrain space. The reason you're having 22 as your magic number is probably because your terrain is located 22 units away from the world origin.

Try to use this instead:

height = Terrain.activeTerrain.SampleHeight(cube.position) 
       + Terrain.activeTerrain.transform.position.y;