CodeSnip: Unexpected behavior with C# auto-implemented properties
page 1 of 1
Published: 14 May 2008
Abstract
In this code snippet, Joseph examines a scenario of an unexpected behavior which will happen while using C# auto-implemented properties with reflection. After providing a step-by-step description of the scenario, he provides the complete code listing of all the C# files used in the sample project along with a screenshot of the final output and the relevant Visual Studio 2008 project.
by Joseph Chahine
Feedback
Average Rating: 
Views (Total / Last 10 Days): 6017/ 78

Code

Listing 1: Employee.cs

using System;
namespace CompilerGeneratedProps
{
    public class Employee : Person
    {
        //Fields
        protected string Title;
    }
}

Listing 2: Person.cs

using System;
namespace CompilerGeneratedProps
{
    public class Person
    {
        //Fields
        protected string _LastName; //Declared protected for extensibility.
 
        //Properties
        public string FirstName { get; set; } //Auto-implemented property.
 
        public string LastName
        {
            get
            {
                return this._LastName;
            }
            set
            {
                this._LastName = value;
            }
        }
    }
}

Listing 3: Program.cs

using System;
using System.Reflection;
 
namespace CompilerGeneratedProps
{
  public class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Fields seen in an instance of Person");
      Console.WriteLine("-------------------------------------------------------");
 
      Person objPerson = new Person();
      foreach (FieldInfo fi in 
        objPerson.GetType().GetFields(BindingFlags.Instance | 
        BindingFlags.NonPublic | BindingFlags.Public))
      {
        Console.WriteLine(fi.Name);
      }
 
      Console.WriteLine("\n\n\n\nFields seen in an instance of Employee");
      Console.WriteLine("-------------------------------------------------------");
 
      Employee objEmployee = new Employee();
      foreach (FieldInfo fi in 
        objEmployee.GetType().GetFields(BindingFlags.Instance | 
        BindingFlags.NonPublic | BindingFlags.Public))
      {
        Console.WriteLine(fi.Name);
      }  
            
      Console.Read();
    }
 
  }
}

Output

Figure 1

Downloads

[Download Source]

Conclusion

If auto-implemented properties are used in a parent class, using reflection to collect fields of a derived class won't get the fields corresponding to the aforementioned properties. It's better in this case to code properties the classical way.



User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2009 ASPAlliance.com  |  Page Processed at 11/21/2009 2:56:54 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search