1

I have an interface defined as

public interface INamedReader
{
     string DisplayInfoLine { get; }
     string DisplayName { get; }
}

and a class which implements that interface but it is an internal class

internal class NamedReader : INamedReader, INotifyPropertyChanged
    {
        public NamedReader();

        public string DisplayInfoLine { get; set; }
        public string DisplayName { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public override string ToString();
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "");
        protected virtual bool Set<TField>(ref TField field, TField value, [CallerMemberName] string propertyName = "");
    }

and a class which implements the above NamedReader class

internal class NamedReaderDevice : NamedReader
{
    public NamedReaderDevice();

    public string Id { get; set; }
}

and now i defined class which implements INamedReader

public class ReaderDetails: INamedReader
{
     public string DisplayInfoLine { get; }

     public string DisplayName { get; }
}

I then created a function which return List.

public List<ReaderDetails> GetReaders
{
     var readers = new List<ReaderDetails>();
     var Ireaders = someobject.Getreaders();// Returns the list of NameReaderDevice (which is an internal class).
     // Now i would like cast Ireaders as readers and return.
}

can someone please help me out in this, that would be great.

Ravi Kumar G N
  • 396
  • 1
  • 3
  • 11

1 Answers1

0

You are basically trying to convert one class into an entirely different one, like in this picture, trying to convert Class2 to Class3:

enter image description here

In this scenario, even if they share an interface, you cannot cast between one and the other.

You have a few options:

  1. use a method (extension or otherwise) to convert between classes, using Reflection or serialization (not very efficient)
  2. use a conversion operator (more details here)
  3. return an interface instead of an explicitly implemented class in your Getreaders() method and then use an interface in your application instead of an explicitly implemented class;

In case of (3) if you need or want to further decouple your class implementation, then you may use dependency injection for it (eg. SimpleInjector, accessible through nuget). In that scenario you can for example create objects of said interface in code that does not have acces to the internal class implementing it,

Arie
  • 5,251
  • 2
  • 33
  • 54