Search code examples
c#scopeinference

Change block scope to an object to save on writing the object's name


Is there a way to call members within an object's scope? For example, instead of this:

myObject.Foo();
myObject.value = 0;

To call within the scope of myObject:

myObject.
{
    Foo();
    value = 0;
}

This would only serve to save on typing like the implicit type var does. It seems possible since at compile time it's known of what type myObject is.


Solution

  • No, there is no such syntax available in C#, other than in a call to a constructor, when creating a new instance of the object, you can assign to its public properties.

    For example:

    var obj = new MyObject {
        Value1 = 0;
        Value2 = 1;
        ....
    }