Quantcast
Channel: Visual C# forum
Viewing all articles
Browse latest Browse all 31927

Same object, different namespace, calling the same function

$
0
0

Hello forum,

I cant seem to figure out a more efficient way to do this.  I have three classes, same objects, but different namespaces, and I need to map first two classes to the third class which will also have the same properties.  But I cant figure out how I can use a shared function to do the mapping regardless it is the first or the second class since I need to reference the individual objects in the body of the function.  And even though they have the same properties, they are ultimately different.

So just as an example, I have CatOne and CatTwo, both of these need to be mapped to FinalCat.  And I have the function MapToFinalCat that ideally can take either CatOne or CatTwo as parameter and return FinalCat.  But so far I havent been able to get it to work unless I have two MapToFinalCat function, one taking a CatOne and the other taking a CatTwo.

Any suggestion?

namespace CatOne
{
    public class Cat
    {
        public string Name { get; set; }
        public Kittens BabyKittens { get; set; }
    }

    public class Kittens
    {
        public List<Kitten> Kittens { get; set; }
    }
    public class Kitten
    {
        public string KittenName { get; set; }
    }
}

namespace CatTwo
{
    public class Cat
    {
        public string Name { get; set; }
        public Kittens BabyKittens { get; set; }
    }

    public class Kittens
    {
        public List<Kitten> Kittens { get; set; }
    }
    public class Kitten
    {
        public string KittenName { get; set; }
    }
}

namespace FinalCat
{
    public class Cat
    {
        public string Name { get; set; }
        public Kittens BabyKittens { get; set; }
    }

    public class Kittens
    {
        public List<Kitten> Kittens { get; set; }
    }
    public class Kitten
    {
        public string KittenName { get; set; }
    }
}

public FinalCat.Cat MapToFinalCat(CatOne.Cat oldCat)
        {
            FinalCat.Cat newCat = new FinalCat.Cat();
            FinalCat.Kittens kittens = new FinalCat.Kittens();
            newCat.Name = oldCat.Name;
            
            foreach(CatOne.Kitten oldKitten in CatOne.Kittens)
            {
                FinalCat.Kitten newKitten = new FinalCat.Kitten();
                newKitten.KittenName = oldKitten.KittenName;
                kittens.Kittens.Add(newKitten);
            }
            newCat.BabyKittens = kittens;
            return newCat;
        }



Viewing all articles
Browse latest Browse all 31927

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>