How to convert this method into a generic one? - C#