How does Material.RenderMaterial gets assigned?

Hi in order to create a material and assign it to some RhinoObjects, I based my code on this:

But, I need to create the Mateiral at a different time than the ObjectAttributes are are set.
So, I tried these steps:
-1 Create a Material and add it to the MaterialTable
-2 Create a RenderMaterial for that Material, hopping that the property Material.RenderMaterial will be automatically assigned (it is readonly)
-3 Later in a second script, assign this RenderMaterial to some ObjectAttributes by accessing Material.RenderMaterial

However, reading the property Material.RenderMaterial seems to create a new instance of RenderMaterial, instead of getting the RenderMaterial which was previously created.
Do you know how things should be done so that Material.RenderMaterial gets assigned properly?

Here is the script for steps 1 and 2:

var doc = Rhino.RhinoDoc.ActiveDoc;

var mat = new Material();
mat.Default();
 
//either:
var rm = mat.RenderMaterial;
//or:
var rm = RenderMaterial.CreateBasicMaterial(doc.Materials[ind], doc);

doc.RenderMaterials.Add(rm);

Print(rm.DocumentOwner.Name);
Print(mat.RenderMaterial.DocumentOwner.Name);//Error: DocumentOwner is null

This script gets a null reference for mat.RenderMaterial.DocumentOwner.

And here is the script for step 3:

var att = new ObjectAttributes();
att.RenderMaterial = doc.Materials.FindIndex(ind).RenderMaterial;
att.MaterialSource = ObjectMaterialSource.MaterialFromObject;

I get this error in the second script, also indicating that the Material.RenderMaterial was not assigned:

  1. The material is not attached to a document. (line: 0)

Here a literate script for creating render materials and assigning those to objects:

https://jesterking.github.io/rhipy/create_specific_rendermaterial.html

You can find more examples here:

https://jesterking.github.io/rhipy/

Try to stay away from the old material system, it is not great.