Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading