Search code examples
c#.netdata-annotations.net-standard

Inheritance a class that implements IValidatableObject from .NET Framework to .NET Standard


I have two libraries - the first is in .NET Framework 4.6.1, while the second is in .NET Standard 2.0. (The second one depends on the first one)

The .NET Framework 4.6.1 contains the following class

    public class Class_Framework : IValidatableObject
    {
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            Console.WriteLine();
            return null;
        }
    }

then I am trying to consume that class in my second .NET Standard 2.0 library:

    interface IStandardInterface
    {
        string AProperty { get; set; }
    }

    class Class_Standard : Class_Framework, IStandardInterface
    {
        public string AProperty { get; set; }
    }

    public class MainStandardClass
    {
        public void AMethod()
        {
            IStandardInterface anInstance = new Class_Standard();
        }
    }

I cannot compile this code, because of the following error:

The type 'IValidatableObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

I am awared that there is no DataAnnotations library in .NET standard so I used NuGet System.ComponentModel.Annotations in both .NET Standard and .NET Framework library. The strangest thing is that if I change

IStandardInterface anInstance = new Class_Standard();

to

var anInstance = new Class_Standard();

then everything is OK. Do you have any suggestion how/if it is possible to inherits a class that implements IValidatableObject from .NET Framework library? Thank you


Solution

  • Not doable, period. A netstandard 2.0 library can only inherit from a netstandard 2.0 library, not a full .NET library.

    This is per definition.

    You will either have to split class hierarchies or move your other library over. We do not know enough for recommending a decent approach here.