Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!