Click here to Skip to main content
15,891,748 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Not able to get value of generic type T

C#
public class TableManagerOf<T> where T : IComparable
   {
       void test()
       {
           var obj = typeof(T);
           m_Properties = typeof(T).GetProperties();
           foreach (var item in m_Properties)
           {
               var value = item.GetValue(obj);
           }
       }
   }


What I have tried:

I have been trying a lot to understand how generic type works in c#
Posted
Updated 10-Feb-17 14:26pm
v2

IComparable[^] has no properties. It has a single method.

To your other question, generics are pretty simple compared to their cousin templates. Basically a class is created which can accept any class conforming to your constraints. In your case, any class which implements IComparable can be used for T. All you could ever want and more is available in Generics (C# Programming Guide)[^] on MSDN.

Another closely related topic is Covariance and Contravariance[^].
 
Share this answer
 
T is a Type and in your case T should be a defined class or struct that implements IComparable. But it is important to remember that T is just defining the requirement at time of writing your code, meaning it is about a class and not about an object instance.
The call to GetProperties() works fine but you do not have an instance. So whatever properties T would have, from which object would you expect the values? You need an instance for that. In your code you assign typeof(T) to obj, but typeof(T) gives you the Type and not an instance of T. The GetProperties on the next line is a method of Type and not of T. If you want your test code working using an instance of T try the following:
public class TableManagerOf<T> where T : IComparable, new()
    {
        void test()
        {
            var obj = new T();
            m_Properties = typeof(T).GetProperties();
            foreach (var item in m_Properties)
            {
                var value = item.GetValue(obj);
            }
        }
    }


The additional new() is to make sure T is a class with a default constructor, so a new instance can be created using a parameterless constructor new T() .

Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900