0

I have a method GetProduct, which returns a Product Object and say, i want to return an additional parameter along with the object, how can i implement it? In my below example , how can i return 'isExists '?

public Product GetProduct()
{
    ---
    ----
   bool isExists = true
   return new Product();
}

I don't want to add that parameter as a property in the Product Class.

Any help on this is much appreciated!

Thanks, Kan

4 Answers 4

2

You could use an out parameter:

public Product GetProduct (out bool isExists)
{
    isExists=true;
    return new Product();
}

and call is like this:

bool isExists;
Product p = GetProduct (out isExists)

although it seems to me that isExists is the sort of property you might want to have in your Product class...

Sign up to request clarification or add additional context in comments.

Comments

0

One way is to rework your method like so:

public bool GetProduct(ref Product product)
{
   ---
   ---
   bool isExists = true;
   product = new Product();
   return isExists
}

This way you can call the method like so:

Product product = null;
if(GetProduct(ref product) {
   //here you can reference the product variable
}

Comments

0

Why not use null?

public Product GetProduct()
{
   bool isExists = true
   if (isExists)
       return new Product();
   else 
       return null;
}

And using it:

var product = GetProduct();
if (product != null) { ... }  // If exists

Comments

0

Couple of suggestions:

Take a look a Dictionary.TryGetValue it behaves in a similar manner, if all you need is to return an object from a collection if it exists.

Product product;
if (!TryGetProduct(out product))
{
  ...
}

public bool TryGetProduct(out Product product)
{
  bool exists = false;
  product = null;
  ...
  if (exists)
  {
    exists = true;
    product = new Product();
  }   

  return exists;
}

If you have other properties you want to return along with the object, you could pass them in as parameters by reference

public Product GetProduct(ref Type1 param1, ref Type2 param2...)
{
  param1 = value1;
  param2 = value2;
  return new Product();
}

Another option is to group all objects into 1 pre-defined .Net class called Tuple

public Tuple<Product, Type1, Type2> GetProduct()
{
  return new Tuple<Proudct, Type1, Type2> (new Product(), new Type1(), new Type2());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.