Search  
Thursday, August 07, 2008 ..:: Blogs ::.. Register  Login
Site Navigation

CreateInstance requires an Instance binding flag
Location: BlogsBemused Musings.NET Tips    
Posted by: KDollard 8/1/2006

I was beating my head against Activator.CreateInstance this morning. It was just telling me the constructor didn’t exist, when I knew it existed. The constructor in this case is private to prohibit any use outside the class. I’m using CreateInstance when I’m creating the class from its generic base class. It also has parameters, so the simplest overload I can use is

 

Public Shared Function CreateInstance ( _

        type As Type, _

        bindingAttr As BindingFlags, _

        binder As Binder, _

        args As Object(), _

        culture As CultureInfo _

) AsObject

 

This isn’t quite as ugly to use as it seems because you can pass Nothing (null in C#) for both the binder and the culture. I tried:

 

Return DirectCast( _

   Activator.CreateInstance(GetType(TList), _

   Reflection.BindingFlags.NonPublic, _

   Nothing, _

   New Object() {dr}, _

   Nothing), TList)

 

The problem I encountered is that you also need to specify BindingFlags.Instance.

 

Return DirectCast( _

   Activator.CreateInstance(GetType(TList), _

   Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance, _

   Nothing, _

   New Object() {dr}, _

   Nothing), TList)

 

In retrospect, this isn’t really onerous, it’s just something you need to know when using this method.

Permalink |  Trackback
Blog_List
Search_Blog
Blog_Archive
Copyright (c) 2008 The Source For Information On Code Generation in Microsoft .NET   Terms Of Use  Privacy Statement