简体   繁体   中英

Elegant way to check if .Net object is empty

I have an X509Certificate2 property, and I want to check in the set section, if the value that was set is empty. When I try to access to any X509Certificate2 property such as publickey, I got this exception: System.Security.Cryptography.CryptographicException occurred in mscorlib.dll .

sure, I can write something such this example:

private static X509Certificate2 _certificate;

    public X509Certificate2 Certificate
    {
        get
        {
            return _certificate;
        }
        set
        {
            try
            {
                if (value.PublicKey != null)
                    _certificate = value;
            }
            catch(CryptographicException)
            {
                _certificate = null;
            }

        }
    } 

but I want a nicer way, does any one have an idea?

MSDN said "The key value is not an RSA or DSA key, or the key is unreadable." So maybe yours algorithm is not RSA or DSA. Check what returns GetKeyAlgorithm()

You can use the simple option - access the Handle property:

public X509Certificate2 Cretificate
{
   get { return _certificate; }
   set { _certificate = value.Handle == IntPtr.Zero ? null : value}
}

as I know, otherwise when you define:

X509Certificate2 cert = new X509Certificate2();

and will try to set your certificate with the empty cert - you might get an exception.

You can use the null coalescing operator :

public X509Certificate2 Certificate     
{
     get { return _certificate; }
     set { _certificate = value.PublicKey ?? null; }
}

Basically:

_certificate = value.PublicKey is it isn't null, else it equals null.

But now writing this, I think that will not work, so might need to use a ternary :

public X509Certificate2 Certificate     
{
     get { return _certificate; }
     set { _certificate = value == null ? null : value.PublicKey; }
}

Which means:

_certificates = null if value is null, else it equals value.PublicKey

I think this is the right approach since your value being null will cause the Exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM