How to create an instance of a .NET Generic class in Dyalog?

The Dyalog "Knowledgebase". This forum is read-only
Forum rules
The FAQ is a read-only forum which is in general updated only by employees of Dyalog Ltd. It replaces the FAQ page which existed under http://www.dyalog.com. Rather than rejecting other posts to this forum, such posts will be put in a moderation queue, and moved to a more appropriate forum.

How to create an instance of a .NET Generic class in Dyalog?

Postby Vince|Dyalog on Fri Aug 27, 2021 11:52 am

How do I access this System.Collections.Generic.List`1 class?

It is a “generic” (i.e its full name is List<T>), which means that you need to provide a Type (i.e. a class) for “T”.

We do not have a syntax to do that. So, it is not possible to create one directly from Dyalog.

Having said that, you can use. Type.MakeGenericType (https://msdn.microsoft.com/en-us/library/system.type.makegenerictype(v=vs.110).aspx) to create a Type, and then use Activator.CreateInstance (https://msdn.microsoft.com/en-us/library/wcxyzt4d(v=vs.110).aspx) to create an instance of it.


So, the following code is an example of that, which works in .NET Framework 4

Code: Select all
⎕USING←'' 'System' 'System,System.dll' 'System.Text' 'System.Type'
bytearr←System.Array.CreateInstance(System.Type.GetType⊂'System.Byte')20
listcoltype←Type.GetType⊂'System.Collections.Generic.List`1'
lobj←listcoltype.MakeGenericType(⊂,Type.GetType⊂'System.Byte')
listcol1←Activator.CreateInstance lobj(,⊂bytearr)
Vince|Dyalog
 
Posts: 406
Joined: Wed Oct 01, 2008 9:39 am

Return to Frequently Asked Questions (FAQ)

Who is online

Users browsing this forum: No registered users and 1 guest