3

Consider a scenario where we have a generic method that should be able to return a null-reference of T, thus T has to be nullable.

Kind of like this:

public static T GetNullableTypeTest<T>()
{
    Contract.Requires(!typeof(T).IsValueType || Nullable.GetUnderlyingType(typeof(T)) != null);
    return (T)(object)null;
}

CC doesn't seem to understand at all what we are trying to do, it complains about unboxing null and method calls results in an "unproven" warning.

Are there any ways to enforce this constraint in Code Contracts?

Alex
  • 14,104
  • 11
  • 54
  • 77
  • [Constraints aren't useful](http://stackoverflow.com/q/19831157/1207195) in this scenario and CC can't _understand_ that calls. What you _may_ ("may" because I wouldn't) do is to have separate methods for different T classes or to live happy with a debug build run-time assertion. – Adriano Repetti Jan 19 '15 at 09:27
  • 1
    @AdrianoRepetti Any idea why this is not understood by CC? Do we have any formal definitions about what kind of evaluations we can use and not? – Alex Jan 19 '15 at 09:38
  • 1
    I merely guess CC can't go so _deep_ in function calls to understand it, to replace this check you may use `ContractArgumentValidatorAttribute` (but again I'm guessing, i didn't try). – Adriano Repetti Jan 19 '15 at 09:52
  • @Alex: Last time I checked, there was no documentation at all about what kinds of contracts the Code Contracts analyzer understands, and what kinds of contracts are even necessary because they cannot be automatically deduced from code. That would be one of my biggest complaints about Code Contracts. – stakx - no longer contributing Jan 19 '15 at 10:21

1 Answers1

1

This is not a Code Contracts issue. You should put a constraint on your method, like this:

public static T GetNullableTypeTest<T>() where T : class

This way this method can't be called passing a value type as T. From there on, put meaningful contracts in the body of your method.

Matteo Mosca
  • 7,380
  • 4
  • 44
  • 80
  • 2
    It restricts `T` to be a reference type (first condition in his contract) but it doesn't allow `T` to be `Nullable` (second condition in his contract). – Adriano Repetti Jan 19 '15 at 09:23
  • Then I didn't fully understand the goal. If that's the case I think it cannot be done in a single method, as System.Nullable can't be used in type constraints. – Matteo Mosca Jan 19 '15 at 09:36