2

I'm not sure if what I am trying to do is setup correctly so I am asking for help.

I have a base class, A, that has a public virtual MethodA(...). In Method A I have the following statement:

var recordToValidate = GetBulkRecordsToBeValidated(profileId);
< more code that uses recordToValidate >

In the base class A I define GetBulkRecordsToBeValidated as follows:

internal virtual List<object> GetBulkRecordsToBeValidated(int profileId)
{
   throw new NotImplementedException();
}

I have other classes that inherit from Class A (i.e. Class B inherits from Class A, Class C inherits from Class A, etc).

Each inherited class overrides the GetBulkRecordsToBeValidated which makes a call to the database to return the specific records for that entity. Each entity returns a different model which is why in the base class I have the method return a List of object.

In Class B it looks like this:

internal override List<object> GetBulkRecordsToBeValidated(int profileId)
{
    return makes call to database which returns a List<ModelBRecords>
}

In Class C it looks like this:

internal override List<object> GetBulkRecordsToBeValidated(int profileId)
{
    return makes call to database which returns a List<ModelCRecords>
}

The problem is I am getting the following error in Class B and Class C on the return:

Cannot convert expression type System.Collection.Generic.List ModelBRecords to return type System.Collection.Generic.List object

What do I need to do so I can return different list types to the call to GetBulkRecordsToValidate in Method A of the Base Class A?

dyarosh
  • 21
  • 2
  • What version of .NET are you targeting? – BJ Myers Dec 23 '15 at 20:35
  • 1
    @maksymiuk: [XY Problem](http://meta.stackexchange.com/q/66377/138661). The OP is asking about casting, but what he really needs is a generic base class. – Heinzi Dec 23 '15 at 20:41

2 Answers2

2

As a quick fix, use .Cast<Object>.ToList().

However, you might want to consider making the base class generic like this:

public class A<T>
{
    public void MethodA()
    {
        List<T> recordToValidate = GetBulkRecordsToBeValidated(profileId);
        ....
    }

    internal virtual List<T> GetBulkRecordsToBeValidated(int profileId) // you might want to make this an abstract method instead of virtual
    {
        ....
    }       
}

public class C : A<ModelCRecords>
{
    internal override List<ModelCRecords> GetBulkRecordsToBeValidated(int profileId)
    {
        return makes call to database which returns a List<ModelCRecords>
    }
}
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
1

You can create generic class

class A<T>
{
    public virtual List<T> GetBulkStuff() { throw new Exception(); }
}

class B : A<ModelBRecords>
{
    public override List<ModelBRecords> GetBulkStuff()
    {
        return base.GetBulkStuff();
    }
}
Valentin
  • 5,380
  • 2
  • 24
  • 38