Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking beforehand if `System.Activator.CreateInstance(Of T)` will fail

Tags:

c#

.net

vb.net

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
like image 660
Pacerier Avatar asked May 24 '11 16:05

Pacerier


1 Answers

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));
like image 117
Magnus Avatar answered Sep 20 '22 19:09

Magnus