Generics, reflection setting of property values

generics , csharp , reflection Johannesburg, South Africa
  • 10 years ago

    Hi guys,

    Ran myself into a brick wall trying to accomplish, what is quite easily possible without generics.

    Review the following code:

    01. public abstract class Sniffer<T>
    02. {
    03. public List<T> Sniff(string query)
    04. {
    05. Type type = typeof(T);
    07. foreach (PropertyInfo info in type.GetProperties())
    08. {
    09. info.SetValue(type, "value_to_set", null);
    10. }
    11. }
    12. }

    Line #09 throws and exception on the invocation on the target type, which it cannot determine from 'type'. I tried to get the type back from type, but that only brings back the underlying runtime type, which is also not valid.

    Does any one have an idea on how I can get this model to work, I'm sure that this is possible?

    Thanks, Eric

  • 10 years ago

    Hi Eric,

    In order to set the value of the property you must have an instance of the type class. You can create an instance by going :

    Type type = typeof(T); T instance = Activator.CreateInstance(type)


    info.SetValue(instance, "valuetoset", null);

    Looking at the code however, you should only be returning 1 instance, and not a list of your type?

Post a reply

Enter your message below

Sign in or Join us (it's free).


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In order to understand recursion, one must first understand recursion.”