tags:

views:

165

answers:

3

So... I want to return value when C# function is called. I need a code example (simple summ of a,b values will be ok) Please help

I need something like this ( I know ActionScript so I will write in it):

public function sum(valueA:int, valueB:int):int 
{
   var summ:int = valueA + valueB;
   return summ;
}

How to translate it into C#?

+6  A: 

Here:

public int sum(int valueA, int valueB)
{
    int summ = valueA + valueB;
    return summ;
}

Differences to note:

  • The return type is declared immediately after the public visiblity qualifier
  • Variable types are declared before them
Oded
A: 

As a side-note, C# (3.0 above) also supports the var keyword when declaring variables, which means that you can write:

public int Sum(int valueA, int valueB) { 
  var summ = valueA + valueB; 
  return summ; 
} 

The meaning of var is porbably different than in ActionScript - it looks at the expression used to initialize the variable and uses the type of the expression (so the code is statically-typed). In the example above, the type of summ will be int just like in the version posted by Oded.

(This is often a confusing thing for people with background in dynamic languages, so I thought it would be useful to mention this, especially since var is also a keyword in ActionScript).

Tomas Petricek
and if I need to concat 2 strings vill 'var' work? like ' var summ = valueA + " "+ valueB; '
Blender
Yes, it will work. The compiler knows that `valueA` and `valueB` are both `int` and so it will figure out that you're adding two integers, so the result will also be integer (and therefore it will infer that `summ` is integer)
Tomas Petricek
A: 

Or even so =)

public int Sum ( int valueA, int valueB ) { return valueA + valueB; }

if you don't need to store a result in a function for some purpose.

n535