Using Smart CLR Property as object repository

4 בDecember 2016

the next scenario can be Simple, yet during development it is hard to change design so tricks like that can be awesome.
Consider the following entity.

public class Cat

{

    public string Name;

}

public class Dog

{

    public string Name;

}

class Wrapper

{

    public bool isDog;

    private Dog dog = new Dog() {Name = "Snoopi" };

    private Cat cat = new Cat() {Name = "Tom" };


    public string Name

    {

        get {

            if (isDog)

                return dog.Name;

            else

                return cat.Name;

        }

        set {

            if (isDog)

                dog.Name = value;

            else

                cat.Name = value;

        }

    }

While observing this code it seems that Wrapper class is a Repository for Dog and Cat,
Of course we can sets a common base class or contract, but sometime it is not an option.
Having said that consider 20 Properties for those classes and you get an ugly code.
The news is new Smart Property who enlarge the common CLR property Get-Set functions.


  private T GetPropertyValue<T>([CallerMemberName]string propName = null)

        {

            Object source = isDog ? (Object)dog : cat;


            if (isDog)

            {

                return (T)dog.GetType().GetProperty(propName).GetValue(source,null);

            }

            else

            {

                return (T)cat.GetType().GetProperty(propName).GetValue(source,null);


            }

        }


     private void SetPropertyValue<T>(T value, [CallerMemberName]string propName = null)

        {

            Object source = isDog ? (Object)dog : cat;


            if (isDog)

            {

                dog.GetType().GetProperty(propName).SetValue(source, value);

            }

            else

            {

                cat.GetType().GetProperty(propName).SetValue(source, value);

            }

        }

Those functions use CallerMemberName c# attribute to resolve the Property name , than by reflection we getting inside the object and manipulate Get Set operations.
So the usage is simple:

class Wrapper

    {

        public bool isDog;

        private Dog dog = new Dog() {Name = "Snoopi" };

        private Cat cat = new Cat() {Name = "Tom" };


        public string Name

        {

            get

            {

                return (string)GetPropertyValue<string>();

            }

            set

            {

                SetPropertyValue<string>(value);

            }

        }

And that it.
Just remember that those functions is inside the Wrapper class

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *