AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1631&pId=-1
CodeSnip: Unexpected behavior with C# auto-implemented properties
page
by Joseph Chahine
Feedback
Average Rating: 
Views (Total / Last 10 Days): 8038/ 11

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.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-25 5:34:38 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search