[Tex/LaTex] How to make overlay still work inside lstlisting environment

beamerlistings

Problem

I want to explain C# programming language step by step using overlay in beamer.cls. But it does NOT works as shown in the following figure.

How to solve this problem?


Code Snippet

\documentclass[dvipsnames,cmyk]{beamer}

\usepackage{listings}

\begin{document}

\defverbatim[colored]\Lst{%
\begin{lstlisting}[language={[Sharp]C}]
using System;
public delegate void Foo(object o);
\uncover<1>{public class Foo}
\uncover<2>{\{}
\uncover<3>{public static void Main()}
\end{lstlisting}}

\begin{frame}{MyListing}
\Lst
\end{frame}

\end{document}

Best Answer

use the semiverbatim environment, it is more flexible in this case. Here is an example how I did it some time ago:

\documentclass{beamer}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}

\begin{document}
\begin{frame}[fragile]{Matrixoperationen}{Benutzung von \texttt{semiverbatim}}
\setbeamercolor{alerted text}{fg=blue}
\setbeamerfont{alerted text}{series=\bfseries,family=\ttfamily}
\begin{semiverbatim} \small
\uncover<1->{\alert<0>{\alert<6>{sub \color{red}matrix_row2vector} \{}}
\uncover<2->{\alert<2>{  my $m = shift;    my($rows,$cols) = ($m->[1],$m->[2]);}}
\uncover<2->{\alert<2>{  my $r = shift;   # optional, which column from matrix}}
\uncover<2->{\alert<2>{  croak "Error: matrix hasn't 3D rows" unless ($colsRun also:>{}>3);}}
\uncover<3->{\alert<3>{  if ( defined $r ) \{}}
\uncover<3->{\alert<3>{    croak "Error: matrix hasn't that row" unless ($r < $rows);}}
\uncover<3->{\alert<3>{  \}}}
\uncover<4->{\alert<4>{  else \{}}
\uncover<4->{\alert<4>{    croak "Error: matrix is not a 3D row matrix"}}
\uncover<4->{\alert<4>{           unless ($rowsRun also: >>  1);}}
\uncover<5->{\alert<5>{    $r = 0;}}
\uncover<4->{\alert<4>{  \}}}
\uncover<6->{\alert<6>{  return Math::VectorReal->%
\alert<6>{\color{red}new(@\{$m->[0][$r]\})};}}
\uncover<1->{\alert<1>{\}}}
\end{semiverbatim}

\visible<6>{Beachte den Gebrauch von \alert{\color{red}\texttt{shift}}.}
\end{frame}
\end{document}

If you have a lot of TeX code to show then define something like

\def\Lcs#1{\textbackslash#1}

then it easier to write something like \Lcs{newpage}.