public CandyBase CreateCandy(string name = null) { try { if (String.IsNullOrWhiteSpace(name)) { return(candyType.GetConstructor(CandyDefaults.Select(x => x.GetType()).ToArray()).Invoke(args.ToArray()) as CandyBase); } else { return(candyType.GetConstructor(args.Select(x => x.GetType()).ToArray()).Invoke(args.ToArray()) as CandyBase); } } catch (Exception ex) { Console.WriteLine(ex.InnerException?.Message ?? ex.Message); } throw new ArgumentException("Was not able to create candy! :("); }
// DRY, sorry! :((( public CandyBase CreateCandy(object[] args = null) { foreach (var candyType in CandyType) { try { if (args == null || args.Length == 0) { if (CandyDefaults != null && CandyDefaults.Length > 0) { return(candyType.GetConstructor(CandyDefaults.Select(x => x.GetType()).ToArray()).Invoke(args.ToArray()) as CandyBase); } } else { return(candyType.GetConstructor(args.Select(x => x.GetType()).ToArray()).Invoke(args.ToArray()) as CandyBase); } } catch { continue; } } throw new ArgumentException("No matching type found."); }