Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
my code:
C#
namespace Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
            Type t = typeof(Product);
            PropertyInfo[] proInfo = t.GetProperties();
            foreach (var item in proInfo)
            {
                Console.WriteLine(item.Name);
            }
        }
    }
    public class Product
    {

        public int ProId { get; set; }
        public string ProName { get; set; }
        public string Description { get; set; }
        public decimal UnitPrice { get; set; }
    }
}

I get all properties names as output.But I dont want to show ProId and Decription in the output .How can i do that????
Posted

Depending on your needs another approach could be to use the BrowsableAttribute:

C#
public class Product
    {
        [Browsable(false)]
        public int ProId { get; set; }
        public string ProName { get; set; }
        public string Description { get; set; }
        [Browsable(false)]
        public decimal UnitPrice { get; set; }
    }




C#
Type t = typeof(Product);
PropertyInfo[] proInfo = t.GetProperties();
foreach (var pi in proInfo)
{
   object [] att = pi.GetCustomAttributes(typeof(BrowsableAttribute), false);
                
   if (att.Length > 0)
   {
      BrowsableAttribute b = att[0] as BrowsableAttribute;
      if (b.Browsable)
      {
         Console.WriteLine(item.Name);
      }
   }

}
 
Share this answer
 
You can't retrospectively hide public properties from reflection - it retrieves them regardless.
What you can do is change the access modifiers when you define them to restrict the availability:
C#
public class Product
    {
    protected int ProId { get; set; }
    public string ProName { get; set; }
    internal string Description { get; set; }
    public decimal UnitPrice { get; set; }
    }

Would hide the properties for you.
 
Share this answer
 

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



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