C# Create instance, call method and assign return variable in one line

433 Views Asked by At

Assume the following code:

DeviceCommunicationDao dao = new DeviceCommunicationDao();
var device = dao.GetDeviceById(123); //returns an object of type "Device"

So I want to assign 2 variables. Is there a way to do this in one line? I mean generally, like via a generic extension method? Something like this:

var device = (new DeviceCommunicationDao() as DeviceCommunicationDao dao).GetDeviceById(123);

I am not looking for lectures on how this is a bad idea and what is confusing or not. I am looking for a one-liner that instantiates 2 variables with a generic approach. Cheers!

1

There are 1 best solutions below

3
On

If you really want you can create something based on tuples + deconstruction + passing in a Func. For example:

// in case of using `new()` generic constraint both generic params should be specified
var (dao, device) = CreateAndInvoke<DeviceCommunicationDao, int>(d => d.GetDeviceById(123));

static (T, TResult) CreateAndInvoke<T, TResult>(Func<T, TResult> f) where T : new()
{
    var t = new T();
    return (t, f(t));
}

Or via providing factory:

var (dao, device) = CreateAndInvoke(() => new DeviceCommunicationDao(),d => d.GetDeviceById(123));

static (T, TResult) CreateAndInvoke<T, TResult>(Func<T> fact, Func<T, TResult> f) 
{
    var t = fact();
    return (t, f(t));
}

Or just passing an created instance:

var (dao, device) = InvokeAndReturnBoth(new DeviceCommunicationDao(), d => d.GetDeviceById(123));

static (T, TResult) InvokeAndReturnBoth<T, TResult>(T inst, Func<T, TResult> f)
    => (inst, f(inst));

Though I would not say that this is much more readable/convenient.