How To Return Different Types Of Objects In C# Based On A Input Parameter Type

Introduction

Requirements come like this that you have multiple roles in an organization. Now based on the role you want to return different profiles of same data like for some user you want to show Full data and for some you want to return the medium amount of same data and for some user you want to show only minimal attributes of same data. Now there are multiple ways of doing this like,

  • Based on the user you can hide attributes: At many places, people also use this method they just hide some attributes based on the job role of the user. They just toggle the visibility of fields in data.
  • You write different entities and code altogether to render data for different job roles. People use this also but it is not a good practice. Because this kind of code is not well managed.
  • We can use the concept of inheritance and casting to do the same. The advantage here is that we do not need to toggle the visibility of fields which makes the security of data intact. Security of data is the main issue while toggling visibility because if there is a techie user he can anyway see your data by toggling the visibility himself using inspect element or some other mean. so when there is a need of detail level always throw a limited object. Hiding is not a good idea for a large application.
  • Others

So here we will see methodology C where we will use inheritance and casting concept and will achieve the detail levels.

Let us come into action with a small demo.

Here we have created a console application using Visual Studio 2017 and written code like below just to make you aware of the concept. We have a BaseClass and DerivedClass over here and you will see that DerivedClass inherits BaseClass. Which means BaseClass have fewer details of data and Derived Class will have more details to data. Hence we can easily say DerivedClass is a full profile of data and BaseClass is a low profile of that data.

using System;

namespace DerivedtoBase
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Demo for returning Child class object from Derived class object.");
            DerivedClass derivedObj = new DerivedClass();
            var baseObj = derivedObj.ReturnBase();
            baseObj.TellClass();
            Console.WriteLine("varBase1 = " + baseObj.varBase1);
            Console.WriteLine("varBase2 = " + baseObj.varBase2);
            // This baseObj cannot even access varBase3 because that is part of derived class
            // Console.WriteLine("varBase2 = " + baseObj.varBase3);
            Console.ReadKey();
        }
    }

    public class BaseClass
    {
        public int varBase1 { get; set; }
        public int varBase2 { get; set; }

        public BaseClass()
        {
            varBase1 = 10;
            varBase2 = 15;
        }

        public void TellClass()
        {
            Console.WriteLine("base");
        }
    }

    public class DerivedClass : BaseClass
    {
        public int varBase3 { get; set; }
        public int varBase4 { get; set; }

        public DerivedClass()
        {
            varBase1 = 100;
            varBase2 = 150;
            varBase3 = 200;
            varBase4 = 300;
        }

        public new void TellClass()
        {
            Console.WriteLine("derived class");
        }

        public BaseClass ReturnBase()
        {
            return (BaseClass)this;
        }

        public object ReturnObjectBasedOnInput(string Type)
        {
            if (Type.Equals("Full"))
            {
                return this;
            }
            else
            {
                return (BaseClass)this;
            }
        }
    }
}

You will see here that we have created a full object that is of DerivedClass and we have written a method in DerivedClass to return the ChildClass object of the same DerivedClass object using Casting. Though we have created an object DerivedObj which is having full details in variable baseObj we have just returned the baseObj attributes only. Which is low detail level data. There is no need to hide any attributes. If you will run this code then you will find out baseObj cannot even access varBase3 attribute which is available as part of full profile data in DerivedClass.

The output of the above code comes like this having only two details because we are having full data but we are throwing low-level data only.

Now let us discuss and create a more practical example of this concept. Suppose you are creating a student database where there are two roles students and teachers etc. Now you want to show student data using two profiles Low & Full. So How will we do that? Let us create two data profiles first and write code as below.

using System;

namespace DerivedtoBase
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Demo for returning different detail levels using inheritance in C#.");
            FullProfile fpdata = new FullProfile();
            string profile = "Full";

            if (profile.Equals("Full"))
            {
                Console.WriteLine("---------------------Full Profile------------------------");
                Console.WriteLine("StudentName = " + fpdata.StudentName);
                Console.WriteLine("FatherName = " + fpdata.FatherName);
                Console.WriteLine("CourseName = " + fpdata.CourseName);
                Console.WriteLine("Attendance = " + fpdata.Attendance);
                Console.WriteLine("City = " + fpdata.City);
                Console.WriteLine("DOJ = " + fpdata.DOJ);
                Console.WriteLine("Subject = " + fpdata.Subject);
            }
            else
            {
                Console.WriteLine("---------------------Low Profile------------------------");
                LowProfile baseObj = (LowProfile)fpdata;
                Console.WriteLine("StudentName = " + baseObj.StudentName);
                Console.WriteLine("FatherName = " + baseObj.FatherName);
                Console.WriteLine("CourseName = " + baseObj.CourseName);
                // Only these 3 properties are accessible through baseObj
            }

            Console.ReadKey();
        }
    }

    public class LowProfile
    {
        public string StudentName { get; set; }
        public string FatherName { get; set; }
        public string CourseName { get; set; }

        public LowProfile()
        {
            StudentName = "Rahul Khanna";
            FatherName = "Abhishek Khanna";
            CourseName = "Graduation";
        }
    }

    public class FullProfile : LowProfile
    {
        public int Attendance { get; set; }
        public string Subject { get; set; }
        public string City { get; set; }
        public string DOJ { get; set; }

        public FullProfile()
        {
            StudentName = "Rahul Khanna";
            FatherName = "Abhishek Khanna";
            CourseName = "Graduation";
            Attendance = 15;
            City = "Lucknow";
            DOJ = "28-02-2012";
            Subject = "Physics";
        }
    }
}

Output

Now, let's change the profiledeclaration value in code to low. The output would come as below.

So this is how we can control what kind of object to be rendered. You can also tweak and enhance the code little bit to return data from the database. This demo I have created just for concept purpose. We can write better code while writing it for an org level project.

Conclusion

I always aspire for working on alternatives to doing things. This is just one way of doing it as I mentioned in the introduction of the article. By using this approach when you return object then there is no need to hide properties based on job roles or detail profiles but you altogether use inheritance and casting to achieve the same. This is only one alternative. I am still working and will try to find a better and optimized approach for the same.


Similar Articles