Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Object expressions #125

Closed
Porges opened this issue Jan 28, 2015 · 1 comment
Closed

Proposal: Object expressions #125

Porges opened this issue Jan 28, 2015 · 1 comment

Comments

@Porges
Copy link

Porges commented Jan 28, 2015

The purpose of this is to allow things like:

var sw = Stopwatch.StartNew();
using (new IDisposable { void Dispose() => Console.WriteLine(sw.Elapsed) })
{
    // ... 
}

Currently one can write:

new { x = 1 }

The proposal is that one can also supply behaviour:

new { x = 1 } with { int XSquared => x * 2 }

The with is needed to disambiguate with collection/object initializers. Inside the with block, public visibility is the default.

This is not limited to anonymous types. Existing types can be augmented:

new List<int> { 1, 2, 3 } with { int Htgnel => this.Reverse().Count() }

Under the covers, this will generate a new type. Obviously the type specified needs to be unsealed/not a value type.

Additional interfaces can be implemented:

new List<int> { 1, 2, 3 } with IEquatable<List<int>>
    {
        bool Equals(List<int> other) => this.SequenceEqual(other)
    }

Anonymous types can also implement interfaces:

using (new with IDisposable { void Dispose() => Console.WriteLine("ended") })
{
    // ...
}

The with keyword is optional if the type specified is an interface, as there is no ambiguity with collection/object initializers, which gives the syntax used in the original example.

The last variation is a type with only behaviour, no interfaces or state.

new with { void Do() => Console.WriteLine("Done") }

Here with is required.

@Porges
Copy link
Author

Porges commented Jan 28, 2015

Already covered in #13, but I used the wrong search terms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants