Why use a keyword instead of an assignment in C #?

I studied outthe C # keyword after reading the section on this in C # in Depth. I cannot find an example that shows why the keyword is required to simply assign the value of the return statement. For instance:

public void Function1(int input, out int output)
{
    output = input * 5;
}

public int Function2(int input)
{
    return input * 5;
}

...
int i;
int j;

Function1(5, out i);
j = Function2(5);

Both me and j now have the same meaning. Is it just the convenience of unsigned initialization, =or is there some other meaning that I don't see? I have seen some similar answers that mention that it takes responsibility for initializing the called here . But is all this superfluous, instead of just assigning a return value and not having a void method signature?

+3
source share
7

out , - , .

Int32.TryParse(input, out myVar), true, false . int out.

int myOutVar;

if (Int32.TryParse("2", out myOutVar))
{
   //do something with the int
}else{
    //Parsing failed, show a message
}
+13

out / ref # , . (, Tuple), , out / ref. , , .

+3

, out, .

TryGetValue IDictionary (, myDictionary - IDictionary<string, string>) :

string value = String.Empty;
if (myDictionary.ContainsKey("foo"))
{
  value = myDictionary["foo"];
}

ContainsKey, , , :

string value;
if (!myDictionary.TryGetValue("foo", out value))
{
  value = String.Empty;
}

IMO, out.

+3

, # - :

a,b = func(x,y,z);

, Python . - .

F # , , .

PS: . - http://www.martinfowler.com/bliki/DataClump.html

+2

, Int32.TryParse boolean, out . 0 true, , , , 0. false, .

+1

. TryParse(),

Int32.TryParse("3", out myInt);

bool, , int.

Int32.TryParse("3", myInt);

, ? myInt? TryParse int?

. out, , , return - - .

+1

- ( )

if (ReadSingle<UserRecord>(cmd, out user))
    Cache.Insert(cacheId, user, null,
        DateTime.MaxValue, TimeSpan.FromMinutes(3));

- :

user = ReadSingle<UserRecord>(cmd);
if(null != user)
   // Cache.Insert ...

This simplifies the code a bit to use the logical result (that the record was read from the database) and get the actual record in the variable using the keyword out.

+1
source

All Articles