Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Data Annotations in Interface

Quick question...

If I put a notation in the Interface...

Say [Required]

can I ommit that notation in the C# class for the property?

i.e. can I...

Interface IFoo
{
   [Required]
   string Bar {get; set;}
}

Class Foo : IFoo
{
   string Bar {get; set;}
}

or do I need to just not put the notation in the interface and do this...

Interface IFoo
{
   string Bar {get; set;}
}

Class Foo : IFoo
{
   [Required]
   string Bar {get; set;}
}
like image 857
Captain Redbelly Avatar asked Jun 09 '13 04:06

Captain Redbelly


1 Answers

Placing the Data Annotation in the interface won't work. In the following link there is an explanation as to why: http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/1748587a-f13c-4dd7-9fec-c8d57014632c/

A simple explanation can be found by modifying your code as follows:

interface IFoo
{
   [Required]
   string Bar { get; set; }
}

interface IBar
{
   string Bar { get; set; }
}

class Foo : IFoo, IBar
{
   public string Bar { get; set; }
}

Then it is not clear as to whether the Bar string is required or not, since it is valid to implement more than one interface.

like image 172
Dan Teesdale Avatar answered Nov 03 '22 03:11

Dan Teesdale