0

How do I structure a class or a function/method (or interface) so that as part of a using, I can pass values in the {} brackets?

in the following:

using (var something = new SomeFunction(somevalue) { AnotherValue = anotherValue, AdditionalValue = adValue })
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Kevin Scheidt
  • 95
  • 3
  • 10

2 Answers2

1

Using the brackets {} you can set the public properties of that object after the constructor finished.

AnotherValue and AdditionalValue are properties of SomeFunction

It is called object initializers.

Georg
  • 324
  • 1
  • 7
  • Yours is technically right and thank you, i'm accepting romanoza's as the answer because he provided code that I could use as is. I did not know they were called initializers.. I wish i could accept both of your answers because the two answers combined = the full answer. – Kevin Scheidt Feb 01 '16 at 19:58
1

You code is completely valid. You can write your use clause as:

public class SomeClass: IDisposable
{
    public SomeClass(object somevalue) {
    }

    public int AnotherValue { get; set; }

    public int AdditionalValue { get; set; }

    internal void ImHere() {
        throw new NotImplementedException();
    }

    public void Dispose() {
        throw new NotImplementedException();
    }
}

static void Main(string[] args) {
    object somevalue = null;
    using (var something = new SomeClass(somevalue) { AnotherValue = 1, AdditionalValue = 2 }) {
        something.ImHere();
    }
}
romanoza
  • 4,775
  • 3
  • 27
  • 44