Re: some c# questions!! please send me the answer




Bruce Wood wrote:
> > Why are out parameters a bad idea in .NET? Are they?
>
> "out" parameters aren't a bad idea in .NET. FxCop warns you not to use
> them, but only because other programmers might be unfamiliar with the
> concept. There are situations in which methods return more than one
> result, in which out parameters are the way to go. However, they should
> be rare in most programs, as most methods return only one result.

I forgot to mention the one great "gotcha" if you have more than one
"out" parameter of the same type:

decimal foolTheProgrammer;
GetHeightWidth(out foolTheProgrammer, out foolTheProgrammer);
Console.WriteLine("Fool the programmer is: {0}", foolTheProgrammer);

private void GetHeightWidth(out decimal height, out decimal width)
{
height = 100;
width = height * 2;
height = width + 10;
}

The value "fool" will come back as 210. Notice also that the compiler
can't optimize any statements that involve height and width, because it
can't guarantee that they both won't point to the same location, or
different locations.

As well, the caller is constrained to declare "decimal" variables and
pass them in to the method. Regular functions allow the caller to do
this:

decimal height = GetHeight() * 1000;

where GetHeight could return a decimal, an int, or a short and it would
still work. "out" parameters require precisely the type specified and
nothing else (except for downcasts, of course).

Despite all of this, though, "out" parameters do have their place. It's
best to avoid them when another viable option (such as a property or
method returning a single result) is possible.

.


Loading