1

Assume I've defined an interface with multiple properties, e.g.:

interface IFailable<T>
{
    T Value { get; }
    bool Success { get; }
}

and I want class Foo to expose multiple readonly instances of this, where IFailable properties are calculated from Foo's private non-static data, how would I do that in c#?

In Java its fairly intuitive.

Here's the best I came up in c#, based on https://stackoverflow.com/a/4770231/146567

First create a wrapper:

public class FailableDelegator<T> : IFailable<T>
{
    public delegate T valueDelegate();
    public delegate bool successDelegate();

    private readonly valueDelegate valueHandler;
    private readonly successDelegate successHandler;

    public T Value { get { return valueHandler(); } }
    public bool Success { get { return successHandler(); } }

    public FailableDelegator(valueDelegate v, successDelegate s)
    {
        valueHandler = v;
        successHandler = s;
    }
}

Then use it to define the properties in Foo's constructor:

public class Foo
{
    private double x = 3;
    private double y = -9;
    public readonly FailableDelegator<double> xPlusY;
    public readonly FailableDelegator<double> sqrtY;

    public Foo()
    {
        xPlusY = new FailableDelegator<double>(() => x + y, () => true);
        sqrtY = new FailableDelegator<double>(() => Math.Sqrt(y), () => y>=0);
    }
}

I had to put the definitions in Foo's constructor because I got error "cannot access non-static field in static context" if I attempted it directly on the field.

I'm not keen on this, because for less trivial examples you end up with a huge amount of code in Foo's constructor.

Community
  • 1
  • 1
Sam
  • 581
  • 4
  • 17
  • readonly is what's forcing you to put in constructor. It's like final in java. – weston May 02 '14 at 16:18
  • @weston I meant I can't do this: public readonly FailableDelegator xPlusY = new FailableDelegator(() => x + y, () => true) – Sam May 02 '14 at 16:22
  • Looks like a duplicate of http://stackoverflow.com/questions/7400677/a-field-initializer-cannot-reference-the-non-static-field-method-or-property – Josh May 02 '14 at 21:14

0 Answers0