miri
miri

Reputation: 1691

Define default return value/function of a class?

Can I create a class with a default return value? Lets say if I create an object of this class I get always a specific value, without calling the properties or something else. Example:

int i = new MyIntClass(/*something*/); //will return an int

Actually I would like to use a default function for returning something. Maybe like this:

class MyCalculator()
{
  public double a { get; set; }
  public double b { get; set; }

  MyCalculator(double a, double b)
  {
    this.a = a;
    this.b = b;
  }

  public double DoMath()
  {
    return a*b;
  }
}

/* somewhere else */
double result = new MyCalculator(5.5, 8.7);

result should be the result of DoMath(). Is that possible? I know its maybe not the best example, but something like this would be nice. Any ideas?

Upvotes: 0

Views: 3412

Answers (2)

Jon Hanna
Jon Hanna

Reputation: 113322

If I follow you, you want a MyCalculator to have a double it can be treated as. You can do this with an implicit cast operator overload. Put this in the definition of MyCalculator:

public static implicit operator double(MyCalculator m)
{
  return m.DoMath();
}

However, it somewhat hides what's going on (you called new and got a double) and if you're a heavy user of var you'll find it annoying because you have to then be explicit.

In all, only use implicit if you have a very strong justification for it. Indeed, only use explicit if you have a very strong justification for it, and only use implicit if you've an extremely strong justification.

A good guideline for anything to do with a class' interface is "how sensible or weird will this look to someone who never sees the source code?"

Upvotes: 4

leppie
leppie

Reputation: 117280

You can do an implicit cast.

Example (add to class):

public static implicit operator double(MyCalculator c)
{
  return c.DoMath();
}

Upvotes: 6

Related Questions