Tân
Tân

Reputation: 1

interface property with attribute

I want to declare a class to search some topics with specific key. First, I've declared an interface ISearch

interface ISearch
{
    [Required(ErrorMessage = "Search key must be required.")]
    string Key { get; set; }
    Task<IEnumerable<TopicViewModels>> Search();
}

Then, I want to check Key is null or not via using RequiredAttribute.

My question: How to get the error message to throw to user if Key is null?

I don't want to use this way:

Task<IEnumerable<TopicViewModels>> Search(string key)
{
   if (!string.IsNullOrEmpty(key))
   {
      // start searching....
   }
   // throw error message
}

Upvotes: 0

Views: 222

Answers (3)

Isaac van Bakel
Isaac van Bakel

Reputation: 1862

Interface Member Attributes Are Not Inherited! See Attribute on Interface members does not work

If you want to get the error message itself for display (rather than how you want to display it) you can use reflection.

((RequiredAttribute)((PropertyInfo)typeof(ISearch).GetMember("Key")).GetCustomAttribute(typeof(RequiredAttribute))).ErrorMessage;

Don't use that code snippet, but it should give you the idea.

Upvotes: 1

TVOHM
TVOHM

Reputation: 2742

Is an abstract class appropriate for your case?

public abstract class AbstractSearch
{
    string _key = null;

    public string Key
    {
        get 
        {
            if (_key == null) throw new Exception("Key has not been set.");
            return _key; 
        }
        set 
        { 
            if (value == null) throw new ArgumentNullException("Key");
            _key = value;
        }
    }

    public abstract Task<IEnumerable<TopicViewModels>> Search();
}

public class MySearch : AbstractSearch
{
    public override Task<IEnumerable<TopicViewModels>> Search()
    {
        string key = Key;
        // Start searching...
    }
}

Upvotes: 1

James Dev
James Dev

Reputation: 3009

You will have to add the annotation to your concrete class i.e. your view model. You cannot declare data annotations on your interface.

interface ISearch
{
    string Key { get; set; }
    Task<IEnumerable<TopicViewModels>> Search();
}

class MyViewModel : ISearch
{
    [Required(ErrorMessage = "Search key must be required.")]
    public string Key { get; set; }
    public Task<IEnumerable<TopicViewModels>> Search()
    {
    }
}

Upvotes: 0

Related Questions