Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6898365
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T07:17:12+00:00 2026-05-27T07:17:12+00:00

I am implementing a custom IFormatter to serialize objects into a custom format that

  • 0

I am implementing a custom IFormatter to serialize objects into a custom format that is required by our legacy systems.

If I declare a C# auto property:

[StringLength(15)]
public MyProperty { get; set; }

And then in my custom serialize method I get the serialized fields via:

MemberInfo[] members = 
    FormatterServices.GetSerializableMembers(graph.GetType(), Context);

How can I access the StringLength attribute that decorates the auto Property?

I am currently getting the property info by taking advantage of the <PropertyName>k_backingfield naming convention. I’d rather not rely on this as it seems to be a specific detail of the C# compiler implementation. Is there a better way?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T07:17:13+00:00Added an answer on May 27, 2026 at 7:17 am

    The better way would be to stop relying on private fields for serialization (as FormatterServices.GetSerializableMembers returns) and only use public Properties instead.

    It is a LOT cleaner and works in this specific case.

    But due to legacy code you might want to continue to use FormatterServices.GetSerializableMembers and in this case, no there is no other options for you other than using the naming convention (Or a little bit of IL analysis) and it may break at each new compiler release.

    Just for fun here is some code to do a little bit of IL analysis (It lack ignoring NOOPs and other niceties but should work with most current compilers. If you really adopt such a solution check the Cecil library (written by Jb Evain) as it contains a full decompiler and it’s better than doing it by hand.

    It’s usage is like this :

    void Main()
    {
        var members = FormatterServices.GetSerializableMembers(typeof(Foo));
        var propertyFieldAssoc = new PropertyFieldAssociation(typeof(Foo));
    
        foreach(var member in members)
        {
            var attributes = member.GetCustomAttributes(false).ToList();
            if (member is FieldInfo)
            {
                var property = propertyFieldAssoc.GetProperty((FieldInfo)member);
                if (property != null)
                {
                    attributes.AddRange(property.GetCustomAttributes(false));
                }
            }
    
            Console.WriteLine(member.Name);
            foreach(var attribute in attributes)
            {
                Console.WriteLine(" * {0}", attribute.GetType().FullName);
            }
            Console.WriteLine();
        }
    }
    

    And the code :

    class PropertyFieldAssociation
    {
        const byte LDARG_0 = 0x2;
        const byte LDARG_1 = 0x3;
        const byte STFLD = 0x7D;
        const byte LDFLD = 0x7B;
        const byte RET = 0x2A;
    
        static FieldInfo GetFieldFromGetMethod(MethodInfo getMethod)
        {
            if (getMethod == null) throw new ArgumentNullException("getMethod");
    
            var body = getMethod.GetMethodBody();
            if (body.LocalVariables.Count > 0) return null;
            var il = body.GetILAsByteArray();
            if (il.Length != 7) return null;
    
            var ilStream = new BinaryReader(new MemoryStream(il));
    
            if (ilStream.ReadByte() != LDARG_0) return null;
            if (ilStream.ReadByte() != LDFLD) return null;
            var fieldToken = ilStream.ReadInt32();
            var field = getMethod.Module.ResolveField(fieldToken);
            if (ilStream.ReadByte() != RET) return null;
    
            return field;
        }
    
        static FieldInfo GetFieldFromSetMethod(MethodInfo setMethod)
        {
            if (setMethod == null) throw new ArgumentNullException("setMethod");
    
            var body = setMethod.GetMethodBody();
            if (body.LocalVariables.Count > 0) return null;
            var il = body.GetILAsByteArray();
            if (il.Length != 8) return null;
    
            var ilStream = new BinaryReader(new MemoryStream(il));
    
            if (ilStream.ReadByte() != LDARG_0) return null;
            if (ilStream.ReadByte() != LDARG_1) return null;
            if (ilStream.ReadByte() != STFLD) return null;
            var fieldToken = ilStream.ReadInt32();
            var field = setMethod.Module.ResolveField(fieldToken);
            if (ilStream.ReadByte() != RET) return null;
    
            return field;
        }
    
        public static FieldInfo GetFieldFromProperty(PropertyInfo property)
        {
            if (property == null) throw new ArgumentNullException("property");
    
            var get = GetFieldFromGetMethod(property.GetGetMethod());
            var set = GetFieldFromSetMethod(property.GetSetMethod());
    
            if (get == set) return get;
            else return null;
        }
    
        Dictionary<PropertyInfo, FieldInfo> propertyToField = new Dictionary<PropertyInfo, FieldInfo>();
        Dictionary<FieldInfo, PropertyInfo> fieldToProperty = new Dictionary<FieldInfo, PropertyInfo>();
    
        public PropertyInfo GetProperty(FieldInfo field)
        {
            PropertyInfo result;
            fieldToProperty.TryGetValue(field, out result);
            return result;
        }
    
        public FieldInfo GetField(PropertyInfo property)
        {
            FieldInfo result;
            propertyToField.TryGetValue(property, out result);
            return result;
        }
    
        public PropertyFieldAssociation(Type t)
        {
            if (t == null) throw new ArgumentNullException("t");
    
            foreach(var property in t.GetProperties())
            {
                Add(property);
            }
        }
    
        void Add(PropertyInfo property)
        {
            if (property == null) throw new ArgumentNullException("property");
    
            var field = GetFieldFromProperty(property);
            if (field == null) return;
            propertyToField.Add(property, field);
            fieldToProperty.Add(field, property);
        }
    }
    
    class StringLengthAttribute : Attribute
    {
        public StringLengthAttribute(int l)
        {
        }
    }
    
    [Serializable]
    class Foo
    {
        [StringLength(15)]
        public string MyProperty { get; set; }
    
        string myField;
        [StringLength(20)]
        public string OtherProperty { get { return myField; } set { myField = value; } }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm implementing a custom control that inherits from Control . I want it to
I am implementing a design that uses custom styled submit-buttons. They are quite simply
I'm thinking of implementing a custom auto-complete feature so basically my idea now is
I am currently implementing a custom c# cache provider that I can plug in
Implementing custom DataAnnotationsModelMetadataProvider in ASP.NET MVC2. Assuming the object that is being rendered looks
When implementing a custom membership provider I see that the underlying data model has
I'm implementing a custom Flex component that provides a scrollable viewpoint onto a (possibly
I'm implementing a custom Button class that inherits from System.Windows.Forms.Button , I do a
I'm looking for some pointers on implementing Custom Events in VB.NET (Visual Studio 2008,
I'm implementing a custom control and in this control I need to write a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.