Para Kan
Para Kan

Reputation: 121

C# Converting a string variable to an object type reference

My MVC5 custom Html helper class has following method:

public static bool CheckAccessRight(this HtmlHelper htmlHelper, string Action, string Controller)
{
    string displayName = GetPropertyDisplayName<Controller>(i => i.Action);
    // according to logic return a bool
}

GetPropertyDisplayName method:

public static string GetPropertyDisplayName<T>(Expression<Func<T, object>> propertyExpression)
{
// some code
}

As you can see GetPropertyDisplayName method is expecting a class(a type) and class member as it's parameters.

But in my CheckAccessRight method I'm just receiving class name (string Controller) and member (string Action) as strings.

So obviously I'm getting an error at this segment: <Controller>(i => i.Action);

My question is how to convert these string representations into real classes or another workaround.

Thanks!

Upvotes: 2

Views: 2046

Answers (1)

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29233

I don't think a generic method will work in your case and I'll explain why.

Given a string whose value is a type name, you can get a Type object using the following:

var type = AppDomain.CurrentDomain.GetAssemblies()
              .SelectMany(x => x.DefinedTypes)
              .Single(x => x.Name == typeName);

Now, here's the problem: type will only be known at runtime, because it depends on typeName and typeName is only known at runtime. In generics, type parameters need to be known at compile time (when resolving expressions, other type parameters act as known at compile time, based on the given constraints). This is why there is no workaround for this issue (as far as I can imagine).

Necessarily then, you'll have to resort to runtime resolution of this. The most obvious thing I can imagine is that you can just take the type and analyze what it offers:

public static string GetPropertyDisplayName(Type type, Expression<Func<object, object>> propertyExpression)
{
    // some code   
}

The code varies depending on what information you want to extract from the type, but generally there are methods (like GetMembers(), GetMethods(), GetProperties() and GetCustomAttributes()) that will help you locate what you're looking for.

Upvotes: 2

Related Questions