I have a type (Human) and I want to know if I could do System.Activator.CreateInstance(Of Human)()
. So basically I want to check if Human has a public parameterless constructor / or a public constructor with optional parameters that make it possible to call New Human
without giving any arguments.
Is it possible to check beforehand if System.Activator.CreateInstance(Of T)
will fail? (I mean other than wrapping the statement System.Activator.CreateInstance(Of Human)()
in a Try Catch of course..)
I've tried this but it doesn't work:
Option Strict On : Option Explicit On
Module Test
Public Class Human
Public Sub New(Optional ByVal a As Integer = 1)
End Sub
End Class
Public Sub Main()
Dim c = GetType(Human).GetConstructor(System.Type.EmptyTypes)
MsgBox(c Is Nothing)
End Sub
End Module
To check if the constructor is empty or all paramters are optional:
var hasEmptyOrDefaultConstr =
typeof(Human).GetConstructor(Type.EmptyTypes) != null ||
typeof(Human).GetConstructors(BindingFlags.Instance | BindingFlags.Public)
.Any (x => x.GetParameters().All (p => p.IsOptional));
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