// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; namespace E { public interface IRequestResponse { Exception Exception { get; set; } } public class FindUserByIdResponse : IRequestResponse { public Exception Exception { get; set; } public string User { get; set; } } public class FindPostByIdResponse : IRequestResponse { public Exception Exception { get; set; } public string Post { get; set; } } public class Demo { public FindUserByIdResponse FindUserById(int id) { return new FindUserByIdResponse(); } public FindPostByIdResponse FindPostById(int id) { return new FindPostByIdResponse { Post = "Something" }; } } public class Message { } public class OkMessage : Message { public IRequestResponse Response { get; set; } } public class ErrorMessage : Message { public string Text { get; set; } } public class Util { public static Message ValidateResponse(T response, Func f) where T : IRequestResponse { if(response.Exception != null) { return new ErrorMessage { Text = "Exception: " + response.Exception }; } else if(f(response) == null) { return new ErrorMessage { Text = "Not found" }; } else { return new OkMessage { Response = response }; } } } public class Program { public static void Main(string[] args) { Demo demo = new Demo(); FindUserByIdResponse resp1 = demo.FindUserById(123); Message msg1 = Util.ValidateResponse(resp1, r => r.User); Console.WriteLine(msg1.GetType().FullName); FindPostByIdResponse resp2 = demo.FindPostById(456); Message msg2 = Util.ValidateResponse(resp2, r => r.Post); Console.WriteLine(msg2.GetType().FullName); } } }