Using of ref in methods


Using of ref in methods

Using of ref in methods



public class emp
{
public int empno;
public string ename;
public double salary;
public int target;

public void getsalary(int target, ref double salary)
{
salary = salary * target;
}
public void showemp()
{
Console.WriteLine("{0}{1}{2}", empno, ename, salary);
}


}

namespace ConsoleApplication22
{

class Program
{
static void Main(string[] args)
{

emp e1 = new emp()
{
empno = 101,
ename = "ganesh",
salary = 1000,
target = 5
};

e1.getsalary(5, ref e1.salary);
e1.showemp();
}
}
}



Explanation:

The code snippet demonstrates how to use ref keyword in methods. Class emp with 4 data members and 2 methods.

Method 1:
Get salary takes 2 arguments (int target, ref double salary) where the value of salary is passed as a ref to method.

Method 2:

It just writes the output to console.

In main method

The method 1 is called as

e1.getsalary(5, ref e1.salary);

The method2 is called as

e1.showemp ();


Comments

Author: Sanjay20 Jul 2010 Member Level: Silver   Points : 2

Using ref keyword in method
namespace ref_keyword
{
class keyword
{
static void Main(string[] args)
{
int num = 8;
refsqure(ref num);
Console.WriteLine("Value of num using ref keyword:{0}",num);
}

static void refsqure(ref int inum)//ref used in method
{
inum = inum * inum;
}
}
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: