Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remarks for exception types and Registry class #38930

Merged
merged 10 commits into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/fundamentals/runtime-libraries/microsoft-win32-registry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
title: Microsoft.Win32.Registry class
description: Learn about the Microsoft.Win32.Registry class.
ms.date: 12/31/2023
---
# The Microsoft.Win32.Registry class

[!INCLUDE [context](includes/context.md)]

The <xref:Microsoft.Win32.Registry> class provides the set of standard root keys found in the registry on machines running Windows. The registry is a storage facility for information about applications, users, and default system settings. Applications can use the registry for storing information that needs to be preserved after the application is closed, and access that same information when the application is reloaded. For example, you can store color preferences, screen locations, or the size of a window. You can control this data for each user by storing the information in a different location in the registry.

The base, or root, <xref:Microsoft.Win32.RegistryKey> instances that are exposed by the `Registry` class delineate the basic storage mechanism for subkeys and values in the registry. All keys are read-only because the registry depends on their existence. The keys exposed by `Registry` are:

| Key | Description |
|-------------------------------------------------|--------------------------------------------------------------------|
| <xref:Microsoft.Win32.Registry.CurrentUser> | Stores information about user preferences. |
| <xref:Microsoft.Win32.Registry.LocalMachine> | Stores configuration information for the local machine. |
| <xref:Microsoft.Win32.Registry.ClassesRoot> | Stores information about types (and classes) and their properties. |
| <xref:Microsoft.Win32.Registry.Users> | Stores information about the default user configuration. |
| <xref:Microsoft.Win32.Registry.PerformanceData> | Stores performance information for software components. |
| <xref:Microsoft.Win32.Registry.CurrentConfig> | Stores non-user-specific hardware information. |
| <xref:Microsoft.Win32.Registry.DynData> | Stores dynamic data. |

Once you've identified the root key under which you want to store/retrieve information from the registry, you can use the <xref:Microsoft.Win32.RegistryKey> class to add or remove subkeys and manipulate the values for a given key.

Hardware devices can place information in the registry automatically using the Plug and Play interface. Software for installing device drivers can place information in the registry by writing to standard APIs.

## Static methods for getting and setting values

The <xref:Microsoft.Win32.Registry> class also contains `static` <xref:Microsoft.Win32.Registry.GetValue%2A> and <xref:Microsoft.Win32.Registry.SetValue%2A> methods for setting and retrieving values from registry keys. These methods open and close registry keys each time they're used. So when you access a large number of values, they don't perform as well as analogous methods in the <xref:Microsoft.Win32.RegistryKey> class.

The <xref:Microsoft.Win32.RegistryKey> class also provides methods that allow you to:

- Set Windows access control security for registry keys.
- Test the data type of a value before retrieving it.
- Delete keys.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// <Snippet5>
using System;

public class ToStringEx
{
public static void Main()
{
object value = 12;
string s = value.ToString();
Console.WriteLine(s);
}
}
// The example displays the following output:
// 12
// </Snippet5>
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// <Snippet1>
using System;

public class Person
{
String _name;

public String Name
{
get { return _name; }
set { _name = value; }
}
}

public class PersonWithId : Person
{
String _id;

public string Id
{
get { return _id; }
set { _id = value; }
}
}

public class Example
{
public static void Main()
{
Person p = new Person();
p.Name = "John";
try {
PersonWithId pid = (PersonWithId) p;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}

PersonWithId pid1 = new PersonWithId();
pid1.Name = "John";
pid1.Id = "246";
Person p1 = pid1;
try {
PersonWithId pid1a = (PersonWithId) p1;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}

Person p2 = null;
try {
PersonWithId pid2 = (PersonWithId) p2;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}
}
}
// The example displays the following output:
// Conversion failed.
// Conversion succeeded.
// Conversion succeeded.
// </Snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//<Snippet1>
using System;

class ExceptionTestClass
{
public static void Main()
{
int x = 0;
try
{
int y = 100 / x;
}
catch (ArithmeticException e)
{
Console.WriteLine($"ArithmeticException Handler: {e}");
}
catch (Exception e)
{
Console.WriteLine($"Generic Exception Handler: {e}");
}
}
}
/*
This code example produces the following results:

ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
at ExceptionTestClass.Main()

*/
//</Snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// <Snippet3>
using System;
using System.Reflection;

class Example1
{
public static void Main()
{
int limit = 10000000;
PrimeNumberGenerator primes = new PrimeNumberGenerator(limit);
int start = 1000001;
try
{
int[] values = primes.GetPrimesFrom(start);
Console.WriteLine("There are {0} prime numbers from {1} to {2}",
start, limit);
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}

AppDomain domain = AppDomain.CreateDomain("Domain2");
PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap(
typeof(Example).Assembly.FullName,
"PrimeNumberGenerator", true,
BindingFlags.Default, null,
new object[] { 1000000 }, null, null);
try
{
start = 100;
Console.WriteLine(gen.GetPrimesFrom(start));
}
catch (NotPrimeException e)
{
Console.WriteLine("{0} is not prime", e.NonPrime);
Console.WriteLine(e);
Console.WriteLine("--------");
}
}
}
// </Snippet3>
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// <Snippet2>
using System;

public class IConvertibleEx
{
public static void Main()
{
bool flag = true;
try
{
IConvertible conv = flag;
Char ch = conv.ToChar(null);
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException)
{
Console.WriteLine("Cannot convert a Boolean to a Char.");
}

try
{
Char ch = Convert.ToChar(flag);
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException)
{
Console.WriteLine("Cannot convert a Boolean to a Char.");
}
}
}
// The example displays the following output:
// Cannot convert a Boolean to a Char.
// Cannot convert a Boolean to a Char.
// </Snippet2>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// <Snippet1>
using System;
using System.Runtime.Serialization;

[Serializable()]
public class NotPrimeException : Exception
{
private int notAPrime;

protected NotPrimeException()
: base()
{ }

public NotPrimeException(int value) :
base(String.Format("{0} is not a prime number.", value))
{
notAPrime = value;
}

public NotPrimeException(int value, string message)
: base(message)
{
notAPrime = value;
}

public NotPrimeException(int value, string message, Exception innerException) :
base(message, innerException)
{
notAPrime = value;
}

protected NotPrimeException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{ }

public int NonPrime
{ get { return notAPrime; } }
}
// </Snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// <Snippet2>
using System;
using System.Collections.Generic;

[Serializable]
public class PrimeNumberGenerator
{
private const int START = 2;
private int maxUpperBound = 10000000;
private int upperBound;
private bool[] primeTable;
private List<int> primes = new List<int>();

public PrimeNumberGenerator(int upperBound)
{
if (upperBound > maxUpperBound)
{
string message = String.Format(
"{0} exceeds the maximum upper bound of {1}.",
upperBound, maxUpperBound);
throw new ArgumentOutOfRangeException(message);
}
this.upperBound = upperBound;
// Create array and mark 0, 1 as not prime (True).
primeTable = new bool[upperBound + 1];
primeTable[0] = true;
primeTable[1] = true;

// Use Sieve of Eratosthenes to determine prime numbers.
for (int ctr = START; ctr <= (int)Math.Ceiling(Math.Sqrt(upperBound));
ctr++)
{
if (primeTable[ctr]) continue;

for (int multiplier = ctr; multiplier <= upperBound / ctr; multiplier++)
if (ctr * multiplier <= upperBound) primeTable[ctr * multiplier] = true;
}
// Populate array with prime number information.
int index = START;
while (index != -1)
{
index = Array.FindIndex(primeTable, index, (flag) => !flag);
if (index >= 1)
{
primes.Add(index);
index++;
}
}
}

public int[] GetAllPrimes()
{
return primes.ToArray();
}

public int[] GetPrimesFrom(int prime)
{
int start = primes.FindIndex((value) => value == prime);
if (start < 0)
throw new NotPrimeException(prime, String.Format("{0} is not a prime number.", prime));
else
return primes.FindAll((value) => value >= prime).ToArray();
}
}
// </Snippet2>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net481</TargetFramework>
</PropertyGroup>

</Project>
Loading