I have two classes named ROAD and PATH

public class ROAD
{
    public string getData()
    {
          return "Marlton Road";
    }
}

public class PATH
{
    public string getData()
    {
          return "Tagore Path";
    }
}

Also i have a function named FETCH() in my Static Void Main

FETCH() contains following code

public [B][I]returnType[/I][/B] FETCH(bool flag)
{
    if(flag)
    {
       ROAD obj=new ROAD();
       return obj;
    }
    else
    {
       PATH obj=new PATH();
       return obj;
    }
}

Now my question is what should be the return type of function FETCH().
Or is there any other way to implement this logic.

Dani AI

Generated

the right return type depends on what you actually need to do with the result. If the only thing you ever use is the text produced by getData, do not return two different classes at all; just return the data. This keeps the call site simple and eliminates type checks.

// Prefer returning what you need
static string Fetch(bool flag) =>
    flag ? new Road().GetData() : new Path().GetData();

If you really do need to work with both types, ’s suggestions (common interface or abstract base) are the correct direction. Once you have a common abstraction, avoid the boolean parameter smell by making the choice explicit and future-proof (e.g., an enum and a factory). This keeps callers from sprinkling if(obj is ...) checks everywhere and makes adding a new route type trivial.

public enum RouteKind { Road, Path }

static IRoute Fetch(RouteKind kind) => kind switch
{
    RouteKind.Road => new Road(),
    RouteKind.Path => new Path(),
    _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null)
};

A couple of clarifications on replies: mentioned boxing; note that boxing applies to value types. Road and Path are classes (reference types), so returning them as object is not boxing, but it does erase the type and forces fragile runtime checks. , ByRef is not valid C# syntax; while C# supports ref returns for advanced scenarios, it is not appropriate here. Finally, consider .NET naming conventions for readability: classes Road/Path, method GetData, and Fetch using PascalCase.

Recommended Answers

All 5 Replies

You can use Boxing, but I don't recommend doing this. There must be a better way of designing your application.

Basically, return the type "Object" and cast your obj to Object.

public Object FETCH(Boolean flag)
{
   Object myObj = null;
   if(flag)
       myObj = new ROAD();
   else
       myObj = new PATH();
   return myObj;
}

If these are two massively different objects, in my opinion, you have a problem. As your code will *always* need to check what object type it is before using it. So every call you my to the object returned from FETCH you will have to do an object comparison if(obj is ROAD) etc. If this really is the case, I suggest redesigning your application.

If they are similar and they have similar function calls, then please, implement an interface. This way you have no need to check, you can simply return the interface, use the common functionality without performing additional checks. Then, for everything *specific* you can perform your object comparison.

public ByRef FETCH(bool flag)
{
if(flag)
{
ROAD obj=new ROAD();
return obj;
}
else
{
PATH obj=new PATH();
return obj;
}
}

commented: This will not work. Also no code tags. It's still bad design. -2

You could be looking for an "Interface".
Consider this:

using System;

namespace DW_389664
{
   public interface IRouteType
   {
      string getData();
   }

   public class CRoad : IRouteType //a class based on the interface
   {
      public string getData() { return "Marlton Road"; }
   }

   public class CPath : IRouteType //a class based on the interface
   {
      public string getData() { return "Tagore Path"; }
   }

   class Program
   {
      // method that returns a new'ed IRouteType
      private static IRouteType Fetch(bool blnFlag)
      {
         if (!blnFlag) { return new CPath(); }

         return new CRoad();
      }

      static void Main(string[] args)
      {
         IRouteType myRouteType1 = Fetch(true);
         IRouteType myRouteType2 = Fetch(false);

         Console.WriteLine(myRouteType1.getData());
         Console.WriteLine(myRouteType2.getData());
      }
   }
}

You could also be looking for an abstract class with an abstract method.

using System;

namespace DW_389664_2
{
   public abstract class CRouteType
   {
      public abstract string getData();
   }

   public class CRoad : CRouteType
   {
      public override string getData() { return "Marlton Road"; }
   }

   public class CPath : CRouteType
   {
      public override string getData() { return "Tagore Path"; }
   }

   class Program
   {
      // method that returns a new'ed CRouteType
      private static CRouteType Fetch(bool blnFlag)
      {
         if (!blnFlag) { return new CPath(); }

         return new CRoad();
      }

      static void Main(string[] args)
      {
         Console.WriteLine(Fetch(true).getData());
         Console.WriteLine(Fetch(false).getData());
      }
   }
}

Return type can be simply an object.
Then if the other class where you will receive it, you use GetType method:

public class Program
    {
        void YourMethod() //can be main in console!
        {
            object data1 = FETCH(true);
            object data2 = FETCH(false);
            
            //maybe to go through both objects:
            object[] allData = { data1, data2 };
            foreach (object data in allData)
            {
                if (typeof(ROAD) == data.GetType())
                {
                    //is road class
                }
                else if (typeof(PATH) == data.GetType())
                {
                    //is path class
                }
            }
        }

        public object FETCH(bool flag)
        {
            if (flag)
            {
                ROAD obj = new ROAD();
                return obj;
            }
            else
            {
                PATH obj = new PATH();
                return obj;
            }
        }
    }

    public class ROAD
    {
        public string getData()
        {
            return "Marlton Road";
        }
    }

    public class PATH
    {
        public string getData()
        {
            return "Tagore Path";
        }
    }

You can even do it this way, if you wanna check only one object:

object data1 = FETCH(true);
            object data2 = FETCH(false);
                      
            if (typeof(ROAD) == data1.GetType())
            { 
              //is road class
            }
            else if (typeof(PATH) == data2.GetType())
            { 
                //is path class
            }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.