expandafter and csname

I was recently looking for the creation of commands that use the name of another command and I recently discovered \expandafter and \csname instructions. I manage to create simple one using these instructions but I have problems for more complex commands.

Here is a minimal example of my code :

\documentclass{book}
\usepackage{polyglossia}
\setmainlanguage{french}
\usepackage{xargs}
\usepackage{xparse}
\usepackage{ifthen}
\usepackage{amsmath}
\usepackage{mathtools}

\newcommand{\DeclareCentredMathEtype}[2]
{
\DeclareMathOperator*{#1}
{
\begin{minipage}{\widthof{\begin{huge}#2\end{huge}}}\begin{huge}#2\end{huge}\end{minipage}
}
}

\newcommand{\DisplayEtype}[1]
{
\expandafter\let\csname  old#1\expandafter\endcsname\csname #1\endcsname
\expandafter\RenewDocumentCommand\csname #1\endcsname{m o m}{\IfValueTF{##2}{\underset{\substack{##1}}{\overset{##2}{\csname old#1\endcsname}} ##3 }{\underset{\substack{##1}}{\csname old#1\endcsname}{##3}}}
}

\DeclareCentredMathEtype{\test}{A}
\DisplayEtype{test}
\DisplayEtype{sum}

\begin{document}
$\displaystyle\oldtest_{k=0}^{3}{f(k)}$
$\displaystyle\sum{k=0}[3]{f(k)}$
%$\displaystyle\test{k=0}[3]{f(k)}$
\end{document}

In this code, \DisplayEtype is not working correctly. For \sum, it creates \oldsum and redefine \sum without troubles (\sum is redefine as a sum with range indice and exposant). However, in the case of \test, it creates a fatal error (the last commented line).

I think it is because of my \expandafter use here. I have been searching a related topic but so far, I have not found any solution.

Could you tell me what I am missing?

PS : By the way, do you know a simple rule to know where to use \expandafter instruction ?

• apart from the expandafter question beware white space at ends of lines you have lots of missing % – David Carlisle Oct 13 '17 at 12:59
• unrelated to the expandafter question but \begin{minipage}{\widthof{\begin{huge}#2\end{huge}}}\begin{huge}#2\end{huge}\end{minipage} is a rather complicated way of getting a huge text, \vcenter{\hbox{\huge #2}} would produce a centred huge text without setting it twice – David Carlisle Oct 13 '17 at 13:24