How to loop through object’s properties ?

If you are looking to loop through all properties of an object then this article may be helpful for you.

The .NET Framework provides two ways to access metadata on a type:

1) Reflection API provided in the System.Reflection namespace

2) TypeDescriptor class

Folowing is the sample code for TypeDescriptor class.

	public class EmployeeClass
        [Description("Gives/Store employee first name")]
        public string FirstName { get; set; }

        [Description("Gives/Store employee last name")]
        public string LastName { get; set; }

        [Description("Gives/Store employee gender info")]
        public string Gender { get; set; }

        [Description("Gives/Store employee age")]
        public int Age { get; set; }
    EmployeeClass objEmployee = new EmployeeClass()
		FirstName = "Jogendra",
		LastName = "Singh",
		Gender = "Male",
		Age = 28

	PropertyDescriptorCollection pdCollection = TypeDescriptor.GetProperties(objEmployee);

	foreach (PropertyDescriptor property in pdCollection)
		object propDisplayName = property.DisplayName;                
		object propDesc = property.Description;
		object propValue = property.GetValue(objEmployee);

For more info please visit to :-

Programming is Easy…

Use of Obsolete attribute in C#

The Obsolete attribute marks a program entity as one that is no longer recommended for use. Each use of an entity marked obsolete will subsequently generate a warning or an error, depending on how the attribute is configured. For example:

[System.Obsolete("use class B")]
class A
    public void Method() { }
class B
    [System.Obsolete("use NewMethod", true)]
    public void OldMethod()  { }
    public void NewMethod()  { }

In this example the Obsolete attribute is applied to class A and to method B.OldMethod. Because the second argument of the attribute constructor applied to B.OldMethod is set to true, this method will cause a compiler error, whereas using class A will just produce a warning. Calling B.NewMethod, however, produces no warning or error.

The string provided as the first argument to attribute constructor will be displayed as part of the warning or error. For example, when you use it with the previous definitions, the following code generates two warnings and one error:

// Generates 2 warnings:
A a = new A();
// Generate no errors or warnings:
B b = new B();
// Generates an error, terminating compilation:

Two warnings for class A are generated: one for the declaration of the class reference, and one for the class constructor.

The Obsolete attribute can be used without arguments, but including an explanation of why the item is obsolete and what to use instead is recommended.

The Obsolete attribute is a single-use attribute and can be applied to any entity that allows attributes. Obsolete is an alias for ObsoleteAttribute.


References :-


Programming is Easy….