-1

I have these codes which deserialize xml files into C# objects for further processing. All these works. But the problem is there are two different types of xml files. One for monthly and one for daily. The xml schemas for these two files are different but some schemas are the same.

This is the code

var serializer = new XmlSerializer(typeof(Daily.ABC));

using (TextReader reader = new StreamReader(new FileStream(filePath, FileMode.Open)))
{
    var pfaCollection = (Daily.ABC)serializer.Deserialize(reader);

    foreach (var entity in pfaCollection.Records.Entity)
    {
        IngestEntity(entity);
    }
}

and this is for monthly:

var serializer = new XmlSerializer(typeof(Monthly.Entity.ABC));

                using (TextReader reader = new StreamReader(new FileStream(filePath, FileMode.Open)))
                {
                    var pfaCollection = (Monthly.Entity.ABC)serializer.Deserialize(reader);

                    foreach (var entity in pfaCollection.Entity)
                    {
                        IngestEntity(entity);
                    }
                }

As you can see the classes are different but since there are some common schema, I created a method for both. DRY. And my IngestEntity method is below:

 private void IngestEntity(? EntityData){}
Steve
  • 2,963
  • 15
  • 61
  • 133
  • Your question seems to lack an actual question, other than the broadly-stated one in the title. See duplicate for the answer to that one. If you need more help, post a new question but this time be sure to provide a good [mcve], along with a detailed explanation of what that code does, how that's different from what you want, what you've tried so far to fix it, and what _specifically_ you need help with. – Peter Duniho Feb 11 '21 at 08:05

1 Answers1

1

You could make the two classes inherit from the same base class:

class ABCBase { }
class DailyABC   : ABCBase { }
class MonthlyABC : ABCBase { }

private void IngestEntity(ABCBase entity)
{
    // common code here 
    dosomething(entity.foo);

    if(entity is DailyABC daily)
    {
      // daily code here
    }

    if(entity is MonthlyABC daily)
    {
      // monthly code here
    }
}

I'm not sure if doing this is a good idea though -- that entirely depends on context.

galdin
  • 12,411
  • 7
  • 56
  • 71