-1

Consider the following example, here int i is passed for the reference.

My question is, Can i pass a reference type to out? like object (i.e) static void sum(out OutExample oe)

class OutExample
{
   static void Sum(out int i)
   {
      i = 5;
   }
   static void Main(String[] args)
   {
     int val;
     Sum(out val);
     Console.WriteLine(val);
     Console.Read();
   }
}   

Now the below code having some error,

class OutExample
{
  int a;
   static void Sum(out OutExample oe)
   {
    oe.a = 5;
   }
   static void Main(String[] args)
   {
    int b;
    OutExample oe1=new OutExample();
    Sum(out oe);
    oe.b=null;
    Console.WriteLine(oe.b);
    Console.Read();
   }
   }   

Finally Got the Answer!

class OutExample
{
int a;
int b;

static void Sum(out OutExample oe)
 {
   oe = new OutExample();
   oe.a = 5;
 }

static void Main(String[] args)
{ 
   OutExample oe = null; 
   Sum(out oe);
   oe.b = 10;
   Console.WriteLine(oe.a);
   Console.WriteLine(oe.b);
   Console.Read();
}
} 
Balaji
  • 1,375
  • 1
  • 16
  • 30

3 Answers3

1

Yes...

static void Sum(out OutExample oe)
{
    oe = null;
    // or: oe = new OutExample();
}
class OutExample {}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

You must create a new OutExample inside the Sum method:

class OutExample
{
   int a;
   int b;

   static void Sum(out OutExample oe)
   {
       oe = new OutExample();
       oe.a = 5;
   }

   static void Main(String[] args)
   { 
       OutExample oe = null; 
       Sum(out oe);
       oe.b = 10;
       Console.WriteLine(oe.a);
       Console.WriteLine(oe.b);
       Console.Read();
   }
} 
t3chb0t
  • 16,340
  • 13
  • 78
  • 118
1

I would suggest you to rethink something. Reference type are a reference to a storage location. Passing it in out you are passing a reference to this references. Why don't you pass directly by ref?

faby
  • 7,394
  • 3
  • 27
  • 44
  • I think @Balaji is using `out` because he wanted to learn how it works. Questions whether it's a good or a bad practice will come later :-) – t3chb0t Dec 18 '14 at 11:50