locked
convert T to typeof RRS feed

  • Question

  • User-1045082127 posted

    hi there

    I want to send class name as parameter to generic method to something like:

    public static IEnumerable<string>  GetPropertyName <T> () where T:class
            {
                    foreach (PropertyInfo p in typeof(T).GetProperties())
                        yield return p.Name.Substring(0, p.Name.IndexOf(' ')) + ' ' + 
                        p.PropertyType.ToString().Substring(p.PropertyType.ToString(). IndexOf("System.") + 7);              
                
            }

    whereas T is class name but when i call class with value like : GetPropertyName <ClassA> () 

    null is send and nothing happend

    Saturday, October 20, 2018 4:20 AM

All replies

  • User-369506445 posted

    hi

    you can try below code

    public static IEnumerable<string> GetPropertyName(object obj)
            {
                List<string> list = new List<string>();
    
                Type type = obj.GetType();
                PropertyInfo[] properties = type.GetProperties();
    
                foreach (PropertyInfo property in properties)
                {
                    list.Add("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
    
                }
    
                return list;
            }

    and use

      var result= MyClass.GetPropertyName(new ClassA());

    Saturday, October 20, 2018 5:53 AM
  • User-369506445 posted

    another example with Generic type

    public static IEnumerable<string> GetPropertyName<T>()
            {
                List<string> list = new List<string>();
    
                var obj = (T)Activator.CreateInstance(typeof(T));
                Type type = obj.GetType();
                PropertyInfo[] properties = type.GetProperties();
    
                foreach (PropertyInfo property in properties)
                {
                    list.Add("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
    
                }
    
                return list;
                 
            }

    use

     var result= MyClass.GetPropertyName<ClassA>();

    Saturday, October 20, 2018 6:53 AM
  • User303363814 posted

    You haven't show ClassA but I would guess that it does not have any properties.  Do you know the difference between a Property and a Field?

    Use the debugger to discover what is happening.

    Sunday, October 21, 2018 11:41 PM