You can simplify the code using the general method:
private static T Make<T>() { return (T)Activator.CreateInstance(typeof(T)); } public FirstObj First(string one, string two) { return rpc == null ? Make<FirstObj>() : rpc.First(one, two); } public SecondObj Second(string one) { return rpc == null ? Make<SecondObj>() : rpc.Second(one); } public ThirdObj Third() { return rpc == null ? Make<ThirdObj>() : rpc.Third(); }
If FirstObj , SecondObj and ThirdObj are all classes, not struct or primitives, and rpc never returns null for them, you can do this:
public static T RpcOrDefault<T>(T obj) where T : class { return obj ?? (T)Activator.CreateInstance(typeof(T)); }
and name him
FirstObj first = RpcOrDefault(rpc?.First(one, two));
Pay attention to ? in ?. which protects you from null referential exceptions.
source share