How to check object==null for objects without Constructor?
-
Hello, I need to do following. If object was not initialized then assign variable to it like code below. Right now it throws an error becouse MyCert is not initialized when compared to null. How do I do what I need to do?
X509ChainElement MyCert; foreach (X509ChainElement cert in chain.ChainElements) { if ( MyCert == null) { MyCert = (X509ChainElement) cert; continue; } else { .....; } }
-
Hello, I need to do following. If object was not initialized then assign variable to it like code below. Right now it throws an error becouse MyCert is not initialized when compared to null. How do I do what I need to do?
X509ChainElement MyCert; foreach (X509ChainElement cert in chain.ChainElements) { if ( MyCert == null) { MyCert = (X509ChainElement) cert; continue; } else { .....; } }
artisticcheese wrote:
Hello, I need to do following. If object was not initialized then assign variable to it like code below. Right now it throws an error becouse MyCert is not initialized when compared to null. How do I do what I need to do? X509ChainElement MyCert; foreach (X509ChainElement cert in chain.ChainElements) { if ( MyCert == null) { MyCert = (X509ChainElement) cert; continue; } else { .....; } }
The quickest way is to initialize your object at the beginning. I am assuming you will be doing some processing between your declaration and your foreach loop, otherwise it makes no sense to check for a null because you know it is uninitialized. So it would look like this: X509ChainElement MyCert = null; // do some processing and other things..... foreach (X509ChainElement cert in chain.ChainElements) { if ( MyCert == null) //has not been initialized somewhere before the loop { MyCert = (X509ChainElement) cert; continue; } else { .....; } } But what I don't understand about your code is that only the first element will ever be assigned to MyCert. Of course I only get to see a small snippet and this may be the functionality you want.