There are two completely identical functions that are searched for among the many incoming objects, the first object with an interface, let's call it X, and the whole difference is that they give objects with different interfaces, tell me how in C # to specify the type of the returned element in the function not through a code but through a variable

Example:

IMyTextPanel getTextPanel() { List<IMyTextPanel> TextPanels = new List<IMyTextPanel>(); GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(TextPanels); IMyTextPanel TextPanel; if (TextPanels.Count > 0) return TextPanels[0]; return null; } IMyGyro getGyro() { List<IMyGyro> Gyros = new List<IMyGyro>(); GridTerminalSystem.GetBlocksOfType<IMyGyro>(Gyros); IMyGyro Gyro; if (Gyros.Count > 0) return Gyro = Gyros[0]; return null; } 

I would like something on the similarity:

 getCube(string interface) { List<interface> Cubes= new List<interface>(); GridTerminalSystem.GetBlocksOfType<interface>(Cubes); if (Cubes.Count > 0) return Cubes[0]; return null; } 

but the program swears at it

I understand that the function should have a certain format returned, something like obj, but inside I don’t know what should be

    1 answer 1

    I think this is a suitable use for generics.

     T GetWhatever<T>() where T: class { var items = new List<T>(); GridTerminalSystem.GetBlocksOfType<T>(items); return Items.FirstOrDefault(); } 

    and call accordingly as TextPanel tp = GetWhatever<IMyTextPanel>(); or IMyGyro gyro = GetWhatever<IMyGyro>(); .

    You may need other constraints on T if GetBlocksOfType imposes GetBlocksOfType .

    • one
      And yes, why GetBlocksOfType n't GetBlocksOfType return the result via the return value? - VladD
    • The fact is that it returns nothing void, but only forms a list spaceengineerswiki.com/IMyGridTerminalSystem/ru - Mcile
    • @Mcile: Ah, this is not your interface, but third-party. Then this is a question for them, not for you, of course. - VladD