Chapter124:Functionwithmultiplereturn values

No Comments

Section 124.1: “anonymous object” + “dynamic keyword”solution

Youcanreturnananonymousobjectfromyourfunction

publicstaticobjectFunctionWithUnknowReturnValues()

{

///anonymousobject

returnnew{a=1,b=2};

}

Andassigntheresulttoadynamicobjectandreadthevaluesinit.

///dynamicobject

dynamicx=FunctionWithUnknowReturnValues();

Console.WriteLine(x.a); Console.WriteLine(x.b);

Section124.2:Tuplesolution

YoucanreturnaninstanceofTupleclassfromyourfunctionwithtwotemplateparametersasTuple<string,MyClass>:

publicTuple<string,MyClass>FunctionWith2ReturnValues()

{

returnTuple.Create(“abc”,newMyClass());

}

Andreadthevalueslikebelow:

Console.WriteLine(x.Item1);

Console.WriteLine(x.Item2);

Section124.3:RefandOutParameters

TherefkeywordisusedtopassanArgumentasReference.outwilldothesameasrefbutitdoesnotrequirean assignedvaluebythecallerpriortocallingthefunction.

RefParameter:Ifyouwanttopassavariableasrefparameterthenyouneedtoinitializeitbeforeyoupassitas ref parameter to method.

OutParameter:Ifyouwanttopassavariableasoutparameteryoudon’tneedtoinitializeitbeforeyoupassitas out parameter to method.

staticvoidMain(string[]args)

{

inta=2;

intb=3;

intadd=0;

intmult=0;

AddOrMult(a,b,refadd,refmult);//AddOrMult(a,b,outadd,outmult);

Console.WriteLine(add);//5

Console.WriteLine(mult);//6

}

privatestaticvoidAddOrMult(inta,intb,refintadd,refintmult)//AddOrMult(inta,intb, outintadd,outintmult)

{

add=a+b;

mult=a*b;

}

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Recent Posts