How can I get a instance of a generic list with reflection?

How can I get a instance of a generic list with reflection?

Content Index :

How can I get a instance of a generic list with reflection?
Tag : chash , By : Singularity
Date : January 12 2021, 07:00 PM

help you fix your problem I dont' now how can I get a instance of a parameter for Invoke (please see the sample variable "listInstance"). I don't want to create a new list (with Activator.CreateInstance), I want to add an object to the existing list instance. How can I get the object Sample.Samples? , Get the value of the property and invoke the ´Add´ method on it:
class Program
    static void Main(string[] args)
        var cla = new Sample();
        var propertyInfo = cla.GetType().GetProperty("Samples");
        var addMethod = propertyInfo.PropertyType.GetMethod("Add");
        var samples = propertyInfo.GetValue(cla); // retrieve property value
        var newSample = new Sample();

        addMethod.Invoke(samples, new[] { newSample });

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Creating a generic IList instance using reflection

Tag : chash , By : ffmmjj
Date : March 29 2020, 07:55 AM
This might help you I am trying to create a generic list of objects using reflection. The below code throws an error Cannot create an instance of an interface. . I could change the IList to List and it works fine, but I was wondering if there is way to get this working with an IList. , you'll have to instatiate a concrete class so if you do
var type = Type.GetType(typeof (List<T>).AssemblyQualifiedName);
var list = (Ilist<T>)Activator.CreateInstance(type);

Get generic instance generic type using reflection

Tag : chash , By : user121350
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Given:
typeof(List<string>).GetGenericTypeDefinition() == typeof(List<>)

Reflection: Type of item contained in non-generic subclass of generic list

Tag : chash , By : Hans-Inge
Date : March 29 2020, 07:55 AM
I wish this helpful for you
var elementType = (
    from iface in myList.GetType().GetInterfaces()
    where iface.IsGenericType
    where iface.GetGenericTypeDefinition() == typeof(IList<>)
    select iface.GetGenericArguments()[0])

Add instance of Generic List to object using reflection

Tag : chash , By : pdkent
Date : March 29 2020, 07:55 AM
will help you Im running the code from your question with some minor changes to make it compile and it seems to work fine:
void Main()

public static T Parse<T>() where T : new()
   var returnObj = new T();
   PropertyInfo[] properties = typeof(T).GetProperties();
   foreach (PropertyInfo p in properties)
     // Get a meaningful property name
     string ins = p.PropertyType.Name;
        // populate int
        case "Int32":
           p.SetValue(returnObj, 1 , null);

        // populate list
        case "IList`1":
           var list = new List<string>();
           // This will throw the exception 'Parameter count mismatch.'
           p.SetValue(returnObj, list, null);
   return returnObj;

public class Foo
 public virtual int someInt {get; set;}
 public virtual IList<string> list {get; set;}
public class Foo
 public virtual int someInt {get; set;}
 public virtual IList<string> this[int key] 
    get{ return null; }

How to add an object to a generic list property of an instance of a class using reflection

Tag : chash , By : NeedOptic
Date : March 29 2020, 07:55 AM
it fixes the issue I have a class structure below. I am getting this error. Am i missing something here? , It should be something like this:
// gets metadata of List<Lecture>.Add method
var addMethod = pi.PropertyType.GetMethod("Add");

// retrieves current LectureList value to call Add method
var lectureList = pi.GetValue(s);

// calls s.LectureList.Add(obj);
addMethod.Invoke(lectureList, new object[] { obj });
Related Posts Related QUESTIONS :
  • How to make a button appear as if it is pressed?
  • C# and Arrow Keys
  • How do you resolve a domain name to an IP address with .NET/C#?
  • Should the folders in a solution match the namespace?
  • How can I evaluate C# code dynamically?
  • CSharpCodeProvider Compilation Performance
  • How can I create Prototype Methods (like JavaScript) in C#.Net?
  • DataTable Loop Performance Comparison
  • CSV string handling
  • What is the best way to do unit testing for ASP.NET 2.0 web pages?
  • High availability
  • What to use for Messaging with C#
  • Accessing a Dictionary.Keys Key through a numeric index
  • ConfigurationManager.AppSettings Performance Concerns
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com