How can I replace a material in terrain ?

This code does nothing. It's not giving any errors but does nothing.
I want to replace and add my own material to the terrain :

[MenuItem("Assets/Get Type")]
    public static void GetTypes()
        var newmat = AssetDatabase.LoadAssetAtPath("Assets/Materials/Univeral Render Pipeline Lit.mat", typeof(Material));
        var newterrainmat = AssetDatabase.LoadAssetAtPath("Assets/Materials/Terrain-Material.mat", typeof(Material));

        var allgameobjects = FindObjectsOfType<GameObject>();

        var terrain = GameObject.Find("Terrain");
        var terraincomponent = terrain.GetComponent<Terrain>();
        terraincomponent.materialTemplate = (Material)newterrainmat;

I find that this code is working but only if after selecting the Get Type you click the material in the assets it's like I need to apply the changes by clicking the Terrain-Material in the Assets only when clicking/selecting it it's applying the changes.

How can I make the changes to be apply in the script ?

According to the docs you also need to set the Terrain.materialType to Terrain.MaterialType.Custom for this to work