1

I am trying to create a custom attribute in console application but it is not working. My custom attribute never gets called. I found a good example here Custom Attribute not being hit but not happy with its implementation.

I am wondering how data annotations works in MVC. we don't have to call it separately.

Is MVC calling those data annotations attribute behind the scene?

I wish to create custom attribute that I can use it on any class property same like data annotations attribute. But calling it separately like in above link is not what i am looking.

Here is what I have tried:

using System;

namespace AttributePractice
{
    [AttributeUsage(AttributeTargets.Property)]
    public class CustomMessageAttribute : Attribute
    {
        public static readonly CustomMessageAttribute Default = new CustomMessageAttribute();

        protected string Message { get; set; }

        public CustomMessageAttribute() : this(string.Empty)
        {
            Console.WriteLine("Default message is empty");
        }

        public CustomMessageAttribute(string message)
        {
            Message = message;
        }

        public string MyMessage =>
            Message;

        public override bool Equals(object obj)
        {
            if (obj == this)
                return true;
            if (obj is CustomMessageAttribute customMessageAttribute)
                return customMessageAttribute.Message == MyMessage;
            return false;
        }

        public override int GetHashCode()
        {
            return MyMessage.GetHashCode();
        }

        public override bool IsDefaultAttribute()
        {
            return Equals(Default);
        }
    }

    public class Person
    {
        //This never works
        // I am looking to use this attribute anywhere without calling it 
        //   separately , same like data annotations
        [CustomMessage("Hello world")] 
        public string Name { get; set; }

        public int Age { get; set; }

        public void DisplayPerson()
        {
            Console.WriteLine(Name);
            Console.WriteLine(Age);
        }
    }

    internal static class Program
    {
        private static void Main(string[] args)
        {
            var personObj = new Person
            {
                Name = "Tom",
                Age = 28
            };

            personObj.DisplayPerson();
        }
    }
}

Can anybody tell me how to make my custom attribute works like data annotation way?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Glenn singh
  • 233
  • 1
  • 6
  • 18
  • 3
    Attributes don't do anything by themselves. Some code has to look for the attributes and do something with them. That's what happens with data annotation. – Scott Hannen Jul 23 '19 at 17:18
  • 2
    _"Is MVC calling those data annotations attribute behind the scene"_ - yes. It uses reflection to inspect a model's attributes when rendering or validating the model. – CodeCaster Jul 23 '19 at 17:18
  • Thanks ! But how can I make similar reflection or any alternative class for my console app. Any code hint. – Glenn singh Jul 23 '19 at 17:40
  • 1
    You can't use an attribute "without calling it separately". You must write Reflection code to use the attribute. I would suggest starting with the documentation on [`Attribute`](https://learn.microsoft.com/en-us/dotnet/api/system.attribute?view=netframework-4.7.2#remarks) – NetMage Jul 23 '19 at 18:19
  • Please try this one: ‘https://stackoverflow.com/questions/4879521/how-to-create-a-custom-attribute-in-c-sharp’ – Roma Pavliuk Jul 23 '19 at 20:07
  • @RomaPavliuk This is helpful but again old story comes in picture " Reflection has bad performance". I can work with attribute as explained in the link but let's I have made 10 custom attributes, then everytime I have to call it separately via reflection or manually. Is there any way to make generic class, that will look into my application for that custom attribute ? Do I need to make an activator class ? Why data annotation doesn't cause performance issue if it is using reflection ? Any idea how to make that generic class ? – Glenn singh Jul 25 '19 at 12:09
  • @NetMage I agree on this that "we have to call custom attributes separately" but I am looking to make a generic class this will look for those custom attributes. Consider an example of "NewtonSoft.Json", I can use its attribute in console app anytime and it works !.Somewhere that logic is written. we never calls its attribute manually we just use it's attributes like [JsonArray] etc. In my case, I am looking to design a class that will look around my attributes, developer should only use my attribute rather than calling it separately everytime. Any idea how that generic class will look ? – Glenn singh Jul 27 '19 at 16:43
  • @Glennsingh "Reflection has bad performance" - relative to what? If you want to use attributes, you must use Reflection. The Json library is. EF does. There are things you can do to optimize Reflection, but you can't avoid it. Data annotation does cause a performance issue, it just isn't a problem because it is a small, contained issue. – NetMage Jul 29 '19 at 17:43
  • Also, there is no such thing as "calling" a custom attribute. You examine a type to determine if any attributes are associated with it or its members when you need to perform some action with the type. When do you expect `CustomMessage` to affect your program? With what method or action? – NetMage Jul 29 '19 at 17:46

1 Answers1

-2

yes, if you need 10 custom attributes, you should create 10 separate.

Roma Pavliuk
  • 144
  • 8