General function, where the second parameter depends on the first

Is it possible to create a general function in C # where the first parameter is an enumeration (one of several, so it should be general, I think), and the second parameter should be the value from the enumeration selected as the first parameter? I understand that you need to use generics, but I can not figure out how to write such an expression, or if it is possible.

Edit: added code example. I know that this code example does not work, but it illustrates a little the direction I was thinking.

public List<int> Call<EnumValue>(Type enumType, EnumValue enumValue) where EnumValue : Enum.GetValues(typeof(enumType)) { // Something } 
+4
source share
2 answers

I do not think it is possible to have such a compilation time limit. The best you can do is check the runtime:

 public List<int> Call<TEnum>(Type enumType, TEnum enumValue) { if(!enumType.IsAssignableFrom(typeof(TEnum))) throw new ArgumentException(); // Something } 

UPDATE Although I'm not sure why you need to pass Type if in any case it should be the same type as another parameter. Could you get rid of the first parameter?

 public List<int> Call<TEnum>(TEnum enumValue) { Type enumType = typeof(TEnum); // Something } 
+4
source

The only way I could do something like this is to add a condition inside the function and either return something or throw an exception if the parameter is incorrect (with a clear explanation).

+2
source

Source: https://habr.com/ru/post/1492279/


All Articles