The DotNetExtras.Extended library implements useful but not frequently used extension methods for common data types. For the detailed description of the library API, code samples, and usage scenarios, see the API documentation section.
Use the DotNetExtras.Extended library to perform such tasks as:
Deep cloning objects (relies on an external library).
Checking if objects or variables are equivalent (not the same as equal, since different data types, such as int and long will never be considered equal even if they hold the same value).
Checking if a string contains valid JSON or HTML.
Performing various data conversions between data types.
This library has some external dependencies for certain tasks. For example, the deep cloning method uses the DeepCloner package because it provides the most robust implementation of the deep copying objects among available libraries (and we tested a few). If we find a better library in the future, we may switch to it.
The following examples illustrates how to use various extension methods implemented by the DotNetExtras.Extended library.
using DotNetExtras.Extended;
...
bool b = "true".ToType<bool>();
int n = "123".ToType<int>();
DateTime dt = "2021-10-11T17:54:38".ToType<DateTime>();
DateTimeOffset dto = "2021-10-11T17:54:38-03:30".ToType<DateTimeOffset>();using DotNetExtras.Extended;
...
// Will hold: value1, value2, value3
string[] result = "value1|value2|value3".ToArray<string>();
// Will hold: value1, value2, value3
List<string> list = "value1|value2|value3".ToList<string>();
// Will hold: key1=value1, key2=value2
Dictionary<string,string> result = "key1=value1|key2=value2".ToDictionary<string, string>();
// Will hold: [1, 2, 3]
HashSet<int>? hashSet = "1|2|3".ToHashSet();
// Will hold: ["one", "two", "three"]
HashSet<string>? hashSet = "one,two,three".ToHashSet(",");using DotNetExtras.Extended;
...
bool isJson;
// This test can handle both a single element and an array.
isJson = "{\"key1\": \"value1\", \"key2\": \"value2\"}".IsJson(); // true
isJson = "[{\"key1\": \"value1\"}, {\"key2\": \"value2\", \"key3\": 123}]".IsJson(); // true
bool isHtml;
// This test only checks if the string starts with the html tag.
isHtml = "<!DOCTYPE html>hello</html>".IsHtml(); // true
isHtml = "<html>hello</html>".IsHtml(); // trueusing DotNetExtras.Extended;
...
// Will hold:
string escaped = "Hello, world!".EscapeLdapValue();using DotNetExtras.Extended;
...
User clone = original.Clone();List<Sample> elements = new()
{
new(){ Id = 100, ParentId = 1, Name = "Item1" },
new(){ Id = 200, ParentId = 2, Name = "Item2" },
new(){ Id = 300, ParentId = 2, Name = "Item3" },
new(){ Id = 400, ParentId = 3, Name = "Item4" }
};
Sample match = new() { ParentId = 2 };
// Removes two items with ParentId = 2.
int removedCount = elements.RemoveMatching(match);For the complete example and other samples covering additional scenarios, see the source code (and read the comments) of the demo project.