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

  • SEARCH
  • Home
  • 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 9088367
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T21:53:41+00:00 2026-06-16T21:53:41+00:00

I’ve been playing around with custom attributes this evening to see if I could

  • 0

I’ve been playing around with custom attributes this evening to see if I could simplify my caching layer. I have come up with the following:

namespace AttributeCreationTest
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
    public class Cache : Attribute
    {
        public Cache()
        {
            Length = "01h:30m";
        }

        public string Length;
    }

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class CacheIdentifier : Attribute
    {
    }


    [Cache]
    class Class1
    {
        [CacheIdentifier]
        public int ID { get; set; }
    }

    class Class2
    {
        [CacheIdentifier]
        public bool ID { get; set; }
    }

    [Cache(Length = "01h:10m")]
    class Class3
    {
        [CacheIdentifier]
        public string ID { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
            var f1 = new Class1 { ID = 2 };
            var f2 = new Class2 { ID = false };
            var f3 = new Class3 { ID = "someID" };

            DoCache(f1);
            DoCache(f2);
            DoCache(f3);
        }

        public static void DoCache(object objectToCache)
        {
            var t = objectToCache.GetType();

            var attr = Attribute.GetCustomAttribute(t, typeof(Cache));

            if (attr == null) return;

            var a = (Cache)attr;
            TimeSpan span;

            if (TimeSpan.TryParse(a.Length.Replace("m", "").Replace("h", ""), out span))
            {
                Console.WriteLine("name: {0}, {1}", t.Name, span);

                ExtractCacheData(objectToCache);

                return;
            }

            throw new Exception(string.Format("The Length value of {0} for the class {1} is invalid.", a.Length, t.Name)); 
        }

        public static void ExtractCacheData(object o)
        {
            var t = o.GetType();

            foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                if (Attribute.IsDefined(prop, typeof(CacheIdentifier)))
                {
                    Console.WriteLine("   type: {0}, value {1}", prop.PropertyType, prop.GetValue(o));
                    break;
                }

                throw new Exception(string.Format("A CacheIdentifier attribute has not been defined for {0}.", t.Name));
            }
        }

    }
}

The “Cache” attribute will be fleshed out, but I’ve left it minimal whilst learning this area of C#. My idea was to allow easier caching of items, including a simplified method of specifying amount of time to cache an object.

Does this look ok? Would there be any significant performance hits from using this kind of pattern to push items to cache?

I haven’t been able to find any tutorials which cover this kind of idea in any detail, so any advice would be appreciated.

  • 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-06-16T21:53:42+00:00Added an answer on June 16, 2026 at 9:53 pm

    Your implementation seems to be fine, but CacheAttribute object will be one per attribute declaration, not per Class1 object. In other words it doesn’t matter how many objects you will create – if attribute will be assigned only once – the object of that attribute with Length property will be only one in clr.

    But why don’t you want to pass into DoCache method some interface, which you will define some method to retrieve a CacheIdentifier from an object? Such implementation will be more robust, exact, readable. Surely you need to implement it in each class – but I don’t see lots of benefits in passing object into DoCache without specifying any of its responsibilities. For user this API is not intuitive and hard to understand.

    Another point, more advanced if you will – for caching purposes I suggest to look at Aspect-Oriented Programming in general and at PostSharp in particular. This article 5 Ways That Postsharp Can SOLIDify Your Code: Caching makes a great case for implementing caching aspects. Briefly, PostSharp also uses attributes and inserts caching behavior at second step of compilation via IL weaving

    EDIT: If you want nice and clean model without any distortions of non-domain elements, I suggest another AOP technique, known as dynamic interception. Most popular frameworks are LinFu and Castle Dynamic Proxy. As result, you will have your dependencies specified via constructor and IoC container will create proxies, when resolving these dependencies. But the point is that those models will know nothing about that proxies and will use them as there where simple objects. This is somewhat similar to the Decorator pattern

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This could be a duplicate question, but I have no idea what search terms
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have been unable to fix a problem with Java Unicode and encoding. The
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i

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.