lolol
lolol

Reputation: 4390

Property with 2 compatible classes

Permission

public enum PermissionType
{
    Read = 0,
    Write = 1
}

public class Permission
{
    public virtual PermissionType? Type { get; set; }
}

public class PermissionCreate : Permission
{
    [Required]
    [Range(0, 1)]
    public override PermissionType? Type { get; set; }
}

Category

public class Category
{
    public virtual int? Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Permission Permission { get; set; }
}

public class CategoryCreate : Category
{
    [Required]
    public override string Name { get; set; }
    [Required]
    public override PermissionCreate Permission { get; set; }
}

The line public override PermissionCreate Permission { get; set; } throws a error because it needs to match the overridden member type. Is there a way to override the property with both Permission and PermissionCreate since they are compatible?

Upvotes: 2

Views: 65

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83517

You don't need to create a CategoryCreate class. Instead create an Category instance with a PermissionCreate object:

Category Create = new Category();
Create.Permission = new PermissionCreate();

Upvotes: 1

Gabriel Luci
Gabriel Luci

Reputation: 40858

Since your PermissionCreate class already derives from Permission:

public class PermissionCreate : Permission

then you can already assign a PermissionCreate object to your Permission property.

But yes, the derived class must match the parent class exactly. So if you do this:

public class CategoryCreate : Category
{
    [Required]
    public override string Name { get; set; }
    [Required]
    public override Permission Permission { get; set; }
}

Then you can do something like this:

var test = new CategoryCreate { Permission = new PermissionCreate() };

Upvotes: 3

Related Questions