Philippe
Philippe

Reputation: 2029

Why is class constraint on generic type not enforced?

I've got following interface definition

public interface IEncryptor
{
    T Decrypt<T>(byte[] encryptedData) where T : class;
}

with this implementation (which shouldn't be relevant)

internal class ThingyEncryptor : IEncryptor
{
    public T Decrypt<T>(byte[] encryptedData) where T : class
    {
        var encryptedSymmetricKey = encryptedData.Take(SymmetricKeyLength).ToArray();
        var iv = encryptedData.Skip(SymmetricKeyLength).Take(IvLength).ToArray();
        var symmetricEncryptedData = encryptedData.Skip(SymmetricKeyLength + IvLength).ToArray();

        using (var rsa = _certificate.GetRSAPrivateKey())
        {
            var symmetricKey = rsa.Decrypt(encryptedSymmetricKey, RSAEncryptionPadding.Pkcs1);
            var clearData = Decrypt(symmetricEncryptedData, symmetricKey, iv);
            return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(clearData));
        }
    }
}

Reading Constraints on type parameters (C# Programming Guide), it is stated:

If client code uses a type that doesn't satisfy a constraint, the compiler issues an error

I can't see any compiler warning or error when calling the Decrypt method like this (where IMyModel is really an interface and NOT a class):

_encryptor.Decrypt<IMyModel>(x.Patient)

Why?

This code is part of a nestandard20 project.

Upvotes: 2

Views: 64

Answers (1)

Guru Stron
Guru Stron

Reputation: 141565

You are misunderstanding the class constraint, it enforces provided type argument to be a reference type:

The type argument must be a reference type. This constraint applies also to any class, interface, delegate, or array type.

Upvotes: 9

Related Questions