Created
May 26, 2021 19:40
-
-
Save jfoshee/65f00692e39845e247e1ba315b02d0d4 to your computer and use it in GitHub Desktop.
Helpful extension methods for System.Type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Example | |
{ | |
public static class TypeExtensions | |
{ | |
/// <summary> | |
/// Returns a default value for a given Type at run-time. | |
/// </summary> | |
public static object GetDefaultValue(this Type type) | |
{ | |
// https://stackoverflow.com/a/2686723/483776 | |
if (type.IsValueType) | |
{ | |
return Activator.CreateInstance(type); | |
} | |
else | |
{ | |
return null; | |
} | |
} | |
public static bool CanDefaultConstruct(this Type type) | |
{ | |
return !type.IsAbstract && type.HasParameterlessConstructor(); | |
} | |
/// <summary> | |
/// Gets a value indicating if the given type has a parameterless constructor. | |
/// True if it has a parameterless constructor, otherwise false. | |
/// </summary> | |
/// <param name="type">The type.</param> | |
public static bool HasParameterlessConstructor(this Type type) | |
{ | |
// https://github.com/JoshClose/CsvHelper/blob/4cf576ec5524f73fc7894232b23a5969acc48e46/src/CsvHelper/ReflectionExtensions.cs | |
return type.GetConstructor(Array.Empty<Type>()) != null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment