The Duck Typing library allows you to access fields, properties, and methods of an object without having its type definition available at compile time. It achieves this by creating a runtime proxy type that wraps the target object instance.
To use it, you define a proxy (an interface, abstract class, or class with virtual members) that describes the members you want to access. You then use the .As<T>() extension method on your target object to create a proxy instance that implements your definition.
// 1. Define the proxy interface
public interface IDuckAnonymous
{
string Name { get; }
string Version { get; }
}
// 2. Use the .As<T>() extension method on the target object
var anonymousObject = new { Name = ".NET Core", Version = "3.1" };
var proxyInstance = anonymousObject.As<IDuckAnonymous>();
// 3. Access members via the proxy
Console.WriteLine($"Name: {proxyInstance.Name}");