Does MakeGenericType (...) call several times each time creating a new type?

I have an Entity Framework Code First model for which I created a static universal class that has a search method that is called for each item in the list. Recognizing that this is above my head, I thought that creating a static class would improve code clarity and possibly even performance, since you don't need to instantiate in many different places. The goal of all this is to automate what properties you can search for, export, etc. By user.

The main question: if MakeGenericType (...) is called for each element (potentially 1000) that has a property of a reference type, is a common type for this property of a reference type generated once and stored somewhere or generated 1000 times

Indicates any other performance issues or code smells.

public static class SearchUserVisibleProperties<T> { private static List<PropertyInfo> userVisibleProperties { get; set; } static SearchUserVisibleProperties() { userVisibleProperties = typeof(T).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(UserVisibleAttribute))).ToList(); } public static bool search(T item, string searchString) { foreach (PropertyInfo pInfo in userVisibleProperties) { object value = pInfo.GetValue(item); if (value == null) { continue; } if (pInfo.PropertyType == typeof(string) || pInfo.PropertyType.IsValueType) { ...unrelevant string matching code... } else if ((bool)typeof(SearchUserVisibleProperties<>).MakeGenericType(new Type[] { value.GetType() }).InvokeMember(nameof(search), BindingFlags.InvokeMethod, null, null, new object[] { value, searchString })) { return true; } } return false; } } 
+7
generics c # system.reflection ef-code-first
source share
1 answer

The MakeGenericType documentation assumes that the type returned for the same combination of a generic type definition and generic types will be the same:

The Type object returned by MakeGenericType is the same as the Type obtained by calling the GetType method of the resulting constructed type or the GetType method of any constructed type that was created from the same generic type definition using the same type arguments.

Here is a small experiment showing that the above is true:

 var a = typeof(Tuple<,>).MakeGenericType(typeof(int), typeof(char)); var b = typeof(Tuple<,>).MakeGenericType(typeof(int), typeof(char)); var c = typeof(Tuple<int,char>); Console.WriteLine(ReferenceEquals(a, b)); // True Console.WriteLine(ReferenceEquals(a, c)); // True 
+7
source share

All Articles