ranjit r
ranjit r

Reputation: 25

Constraints are not allowed on not generic environment error while casting

I am trying to cast Java lang object to particular class type(Account).

public static T Cast(Object obj) where T : class
{
    var propertyInfo = obj.GetType().GetProperty("Instance");
    return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}

It is throwing an error

Constraints are not allowed on not generic environment.

I've been stuck here for the past two days.

Upvotes: 0

Views: 56

Answers (1)

slfan
slfan

Reputation: 9129

You have to add the generic type parameter <T> to your method

public static T Cast<T>(Object obj) where T : class
{
    var propertyInfo = obj.GetType().GetProperty("Instance");
    return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}

Upvotes: 4

Related Questions