refactoring c# code to simplify porting