Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if Hashtable is read-only in C#
The Hashtable class in C# provides the IsReadOnly property to determine whether the hashtable is read-only or allows modifications. A read-only hashtable prevents adding, removing, or modifying elements after creation.
Syntax
Following is the syntax for checking if a Hashtable is read-only −
bool isReadOnly = hashtable.IsReadOnly;
Return Value
The IsReadOnly property returns a bool value −
-
trueif the Hashtable is read-only -
falseif the Hashtable allows modifications
Using IsReadOnly with Standard Hashtable
A standard Hashtable created using the default constructor is not read-only −
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable hash = new Hashtable();
hash.Add("One", "Katie");
hash.Add("Two", "John");
hash.Add("Three", "Barry");
hash.Add("Four", "David");
hash.Add("Five", "Harry");
Console.WriteLine("Hashtable Key and Value pairs...");
foreach(DictionaryEntry entry in hash) {
Console.WriteLine("{0} and {1}", entry.Key, entry.Value);
}
Console.WriteLine("Is the Hashtable having fixed size? = " + hash.IsFixedSize);
Console.WriteLine("Is Hashtable read-only? = " + hash.IsReadOnly);
}
}
The output of the above code is −
Hashtable Key and Value pairs... One and Katie Five and Harry Three and Barry Two and John Four and David Is the Hashtable having fixed size? = False Is Hashtable read-only? = False
Creating a Read-Only Hashtable
You can create a read-only wrapper around an existing hashtable using Hashtable.ReadOnly() method −
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable originalHash = new Hashtable();
originalHash.Add("1", "A");
originalHash.Add("2", "B");
originalHash.Add("3", "C");
// Create a read-only wrapper
Hashtable readOnlyHash = Hashtable.ReadOnly(originalHash);
Console.WriteLine("Original Hashtable:");
Console.WriteLine("Is read-only? = " + originalHash.IsReadOnly);
Console.WriteLine("\nRead-only wrapper:");
Console.WriteLine("Is read-only? = " + readOnlyHash.IsReadOnly);
Console.WriteLine("\nContents of read-only hashtable:");
foreach(DictionaryEntry entry in readOnlyHash) {
Console.WriteLine("{0} and {1}", entry.Key, entry.Value);
}
}
}
The output of the above code is −
Original Hashtable: Is read-only? = False Read-only wrapper: Is read-only? = True Contents of read-only hashtable: 1 and A 2 and B 3 and C
Comparison
| Hashtable Type | IsReadOnly Value | Can Modify |
|---|---|---|
| Standard Hashtable | false | Yes |
| Read-only wrapper | true | No |
Conclusion
The IsReadOnly property provides a simple way to check if a Hashtable allows modifications. Standard hashtables return false, while read-only wrappers created using Hashtable.ReadOnly() return true.
