dotnet / csharplang

The official repo for the design of the C# programming language
11.49k stars 1.02k forks source link

Anonymous Interface Objects #4301

Open khalidabuhakmeh opened 3 years ago

khalidabuhakmeh commented 3 years ago

Anonymous Interface Objects

Summary

Give C# developers the ability to instantiate anonymous objects that implement a specific interface without first implementing a concrete type.

Motivation

In scenarios where developers need to stub a type for unit tests, it becomes increasingly tedious to create classes that are essentially throw away. They add to the complexity of the project and ultimately increase the noise/signal ratio.

Detailed design

public interface IClient
{
    string Name { get; }
}

// single interface
var client = new IClient {
    Name = "Khalid"
};

We can also implement multiple interfaces on an anonymous type.

public interface IClient
{
    string Name { get; }
}

public interface ICustomer
{
    string AccountNumber { get; }
}

// multiple interface
var client = new IClient, ICustomer {
    Name = "Khalid",
    AccountNumber = "8675309"
};

Method implementations can be implemented using lambda methods.

public interface ICashier
{
    decimal CheckOut(Cart cart);
}

var cashier = new ICashier {
   CheckOut = (c) => cart.Total() * 0.2d;
}

Drawbacks

Alternatives

Create stub types for every new scenario you need an interface.

Use Kotlin. Here is a working example where the khalid instance is an anonymous object that happens to implement the IGreeting interface.

image

    interface IGreeting {
        val name: String
    }

    class Default(override val name: String) : IGreeting

    fun main() {

        val csharp = Default("C# Developer")
        // an anonymous object
        // that implements IGreeting
        val khalid = object: IGreeting {
            override val name: String
                get() = "Khalid (You're Awesome)"
        }

        var folks = listOf(csharp, khalid)
        folks.forEach { println("Hello ${it.name}!") }
    }

Unresolved questions

Design meetings

toupswork commented 3 months ago

@toupswork No one on the LDM think this is beneficial enough to to in the near term. That may change if the landscape of the ecosystem changes. But currently this isn't rising to that level for any of us, or our partner teams.

Bummer. Ok thank you for taking the time to reply.