I would like a clean/compact pattern that is exception safe and will properly dispose rulesKey
, even if something has thrown. This does not appear to be possible with using
(unless maybe 4 using
s but that seems so verbose and opening extra resources that I might not even need opened). What gets me is that this would be so direct/easy in C++. Is there a good solution?
{
RegistryKey rulesKey = null;
rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Internal\\Product");
rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Company\\Internal\\Product");
rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Product");
rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Product");
// Code using rulesKey, might throw
rulesKey.Close();
}
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
C language is considered as the mother language of all the modern programming languages because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of the programming languages follow C syntax, for example, C++, Java, C#, etc.
You could use
using (RegistryKey rulesKey = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Internal\\Product")
?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Company\\Internal\\Product")
?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Product")
?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Product"))
{
//use rulesKey here
}
Since
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. MSDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With