using OUT in a method

P

Pascal

hello everybody !
I get this error 3 times : "The output parameter must be assigned before
the control leaves the current method" (dor dMin and dMax)
this one 1 time : Use of the parameter 'out' is not assigned 'dMax'

This is my first steps in C#: i can't manage(understand) this error.

I would like to test to variables which can be change on form1 by 2 numeric
updown controls before sending them to a UserControl which make some
calculation with these 2 numbers like this :

if (_genData.NumberMin < _genData.NumberMax)
{

S = (int)(_rand.Next((int)_genData.NumberMin,
(int)_genData.NumberMax + 1) / 3) * 3;
}

else
{
//Choisir le nombre cible (_iS) compris dans la fourchette
et le rendre multiple de trois.
// Set the target number (_iS) in the range and make
multiple of three.
So if user modify the value and nudNumMin .Value becomes > nudNumMax
..Value the calculation could send an error in calculating the value S.
That's why i have to test and correct the values before sending them to the
UserControl.



the code in form1 is :
#region min max check
string message = "Attention ! Le nombre maximal doit être > au
nombre minimal. L'erreur sera corrigée";
string caption = "Erreur dans le choix de la taille des nombres.";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result;

// this method checks the values and shows an error message if
// they are not as expected and corrects them to a valid state

public bool CheckMinMaxValues(out int dMin, out int dMax)
{

if ( nudNumMin .Value > nudNumMax .Value )
{
result = MessageBox.Show(message, caption, buttons);
dMin = dMax - 1;
return false;
}
return true;
}
#endregion //min max check

and then :

private void nudNumMax_ValueChanged( object sender, EventArgs e )
{
int dMin = (int)nudNumMin.Value;
int dMax = (int)nudNumMax.Value;
if (!CheckMinMaxValues(out dMin, out dMax))
{
//... do what ever is needed when the check fails
nudNumMin.Value = dMin;
nudNumMax.Value = dMax;
nudNumMax.Value = nudNumMin.Value + 1;
_currParam.GenerationData.NumberMax = (int) nudNumMin.Value
+ 1; // for example

}
_currParam.GenerationData.NumberMax = (int)nudNumMax.Value;
ValueChanged( true );
}

I hope you understand me....
and can help me !
pascal
 
J

Jesse McGrew

hello everybody !
I get this error 3 times : "The output parameter must be assigned before
the control leaves the current method" (dor dMin and dMax)
this one 1 time : Use of the parameter 'out' is not assigned 'dMax'

This is my first steps in C#: i can't manage(understand) this error.

The code you posted doesn't modify dMax, so dMax doesn't need to be an
out parameter. Remove the "out" keyword for dMax and it should work.

Jesse
 
D

Duy Lam

Pascal said:
hello everybody !
I get this error 3 times : "The output parameter must be assigned
before the control leaves the current method" (dor dMin and dMax)
this one 1 time : Use of the parameter 'out' is not assigned 'dMax'

This is my first steps in C#: i can't manage(understand) this error.

I would like to test to variables which can be change on form1 by 2
numeric updown controls before sending them to a UserControl which make
some calculation with these 2 numbers like this :

if (_genData.NumberMin < _genData.NumberMax)
{

S = (int)(_rand.Next((int)_genData.NumberMin,
(int)_genData.NumberMax + 1) / 3) * 3;
}

else
{
//Choisir le nombre cible (_iS) compris dans la
fourchette et le rendre multiple de trois.
// Set the target number (_iS) in the range and make
multiple of three.
So if user modify the value and nudNumMin .Value becomes > nudNumMax
.Value the calculation could send an error in calculating the value S.
That's why i have to test and correct the values before sending them to
the UserControl.



the code in form1 is :
#region min max check
string message = "Attention ! Le nombre maximal doit être > au
nombre minimal. L'erreur sera corrigée";
string caption = "Erreur dans le choix de la taille des nombres.";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result;

// this method checks the values and shows an error message if
// they are not as expected and corrects them to a valid state

public bool CheckMinMaxValues(out int dMin, out int dMax)
{

if ( nudNumMin .Value > nudNumMax .Value )
{
result = MessageBox.Show(message, caption, buttons);
dMin = dMax - 1;
return false;
}
return true;
}
#endregion //min max check

and then :

private void nudNumMax_ValueChanged( object sender, EventArgs e )
{
int dMin = (int)nudNumMin.Value;
int dMax = (int)nudNumMax.Value;
if (!CheckMinMaxValues(out dMin, out dMax))
{
//... do what ever is needed when the check fails
nudNumMin.Value = dMin;
nudNumMax.Value = dMax;
nudNumMax.Value = nudNumMin.Value + 1;
_currParam.GenerationData.NumberMax = (int)
nudNumMin.Value + 1; // for example

}
_currParam.GenerationData.NumberMax = (int)nudNumMax.Value;
ValueChanged( true );
}

I hope you understand me....
and can help me !
pascal

If you use the "out" keyword for the parameters, you must assign the
value to it before go out of method. The "out" keyword requires that.
In your method CheckMinMaxValues(), the value of two "out" parameters
will not be set if the "if" statement is false, so the compiler didn't work.
 
A

Alun Harford

BlackWasp said:
Have a look at http://www.blackwasp.co.uk/CSharpMethodParameters.aspx
for details on output parameters.

Eugh.

While it's always good to have more reference material out there for
people to learn from, I think you need to read the C# specification and
then go back and correct some of the bugs.

In particular:

"So far in the C# Fundamentals tutorial, we have created methods that
accept parameters and return a single value. These parameters are known
as value parameters. This is because when used with value types such as
the numeric types and structures, a copy of the value of the parameter
is passed to the method."

This seems to imply that reference types are not passed by reference.
This is incorrect. They are passed by value (that value is a reference).

"An output parameter is declared using the out keyword before the
parameter type and name. To return a value using the parameter, the
variable is simply assigned a value."

An output parameter doesn't ever 'return' a value. It just represents
the same storage location as the variable used as the argument in the
method invocation.

"When an object based upon any class is passed to a method as a
parameter, the object is passed by reference"

This is wrong.
Reference types passed into value parameters are not passed by reference
- they're passed by value.

"It is possible to create the same behaviour for value types by
declaring a parameter to be a reference parameter"

The behaviour is very different, and you can pass reference types by
reference in the same way.

Alun Harford
 
P

Pascal

Thanks for your help, it took me a while to understand every thing ....
Thanks for the link too.
 
B

BlackWasp

I hear what you are saying but remember that this is a _fundamentals_
tutorial for beginners. Some would say that the semantics are very
important. In my experience they may be but beginners can get too wrapped
up in them and end up confused rather than developing.

eg. Yes, out parameters don't return a value but to beginners, that is the
effect.

It's swings and roundabouts but I am going to tidy up a few sentences.

Cheers!
 
J

Jon Skeet [C# MVP]

I hear what you are saying but remember that this is a _fundamentals_
tutorial for beginners.

I would say that correctly differentiating between passing a reference
by value and passing a parameter by reference is quite fundamental. It
affects the whole mental model of how objects are stored.
Some would say that the semantics are very
important. In my experience they may be but beginners can get too wrapped
up in them and end up confused rather than developing.

I would personally rather beginners took a little bit longer to learn
the fundamentals, than came away with a broken mental model which is
much harder to undo later on.

Jon
 
B

BlackWasp

Hi Jon,

you may be right. There are always two approaches to a problem. As I said
to Alun, I am making some minor changes. I am on the side of the fence that
believes that overall concepts are more appropriate for beginners than
finite details. I can understand that some people disagree with this
approach while some support it.

I have seen plenty of people learn quickly whilst looking at the fine
detail. I have seen equal numbers get bogged down in the detail and lose
interest. As I say, swings and roundabouts but always happy to take
constructive criticism.

--

BlackWasp
www.blackwasp.co.uk
 
J

Jon Skeet [C# MVP]

you may be right. There are always two approaches to a problem. As I said
to Alun, I am making some minor changes. I am on the side of the fence that
believes that overall concepts are more appropriate for beginners than
finite details. I can understand that some people disagree with this
approach while some support it.

There's a difference between omitting fine details and stating
outright falsehoods, however. I'm fine with the idea of leaving a sign
saying "here be dragons" around particularly difficult bits, and
perhaps coming back to them later - but anything which encourages a
beginner to believe something which is actually untrue is a bad thing,
IMO - simply because "unlearning" is difficult.

I'm actually of the belief that the truth about the nature of
references and objects is easier to grasp than we think - it's just
*very* hard to write about clearly. The concept itself isn't that
hard, but explaining it is difficult. Personally I like the analogy of
a piece of paper for value types (to create a copy, you photocopy the
piece of paper) vs a web page for reference types (to tell a friend
about the page, you just give him a copy of the URL, rather than the
page itself).

The bonus of this is that once this fundamental concept has been
grasped, all kinds of things become *much* easier to explain -
assignment, parameter passing, garbage collection, memory allocation
etc.

Jon
 
B

BlackWasp

Yup, still can't disagree with you. That's why I made some changes.

Take a look and drop me an email if you like. Won't post the address here
for obvious spammy reasons but drop me a line on the contact form by all
means.

--

BlackWasp
www.blackwasp.co.uk
 
B

BlackWasp

The Law of Primacy is very important indeed! I certainly would agree that
stating outright falsehoods is a bad thing.

--

BlackWasp
www.blackwasp.co.uk


There's a difference between omitting fine details and stating
outright falsehoods, however. I'm fine with the idea of leaving a sign
saying "here be dragons" around particularly difficult bits, and
perhaps coming back to them later - but anything which encourages a
beginner to believe something which is actually untrue is a bad thing,
IMO - simply because "unlearning" is difficult.

This is such an important principle, it has a name: the "law of primacy".
A Google search turns up surprisingly few hits, given its importance, but
what hits are there do a good job of explaining its importance.
http://www.google.com/search?q="law+of+primacy"
I'm actually of the belief that the truth about the nature of
references and objects is easier to grasp than we think - it's just
*very* hard to write about clearly. The concept itself isn't that
hard, but explaining it is difficult. Personally I like the analogy of
a piece of paper for value types (to create a copy, you photocopy the
piece of paper) vs a web page for reference types (to tell a friend
about the page, you just give him a copy of the URL, rather than the
page itself).

Hmmm...one thing I think can be improved upon in that analogy is that the
piece of paper and the web page aren't really similar. It'd be a better
analogy if the thing representing a value type could be referred to by a
reference type.

Consider, perhaps, instead a library. Books are value types. The card
catalog entries are reference types. You can make copies of the card
catalog easily, and the cards always refer to the same book. But if you
copy a book, you've made a whole new book.

This is inaccurate too, since in reality a single reference doesn't refer
to a value directly, but something that contains a value (either a boxed
value, or a class containing values). But I think it's closer to what's
going on. :)
The bonus of this is that once this fundamental concept has been
grasped, all kinds of things become *much* easier to explain -
assignment, parameter passing, garbage collection, memory allocation
etc.

I very much agree with that. One way or the other, it's important to
teach the fundamentals correctly the first time. Using wrong descriptions
of what's going on can never help with simpler implementations, and it
always leads to incorrect implementations in more complicated scenarios
(how many times have we seen someone passing a class reference by
reference, because they thought that was more efficient than passing the
reference by value?)

Pete
 
J

Jon Skeet [C# MVP]

This is such an important principle, it has a name: the "law of primacy".
A Google search turns up surprisingly few hits, given its importance, but
what hits are there do a good job of explaining its importance.http://www.google.com/search?q="law+of+primacy"

I'm glad it's a properly documented phenomenon rather than just my
intuition (and observations on newsgroups).
Hmmm...one thing I think can be improved upon in that analogy is that the
piece of paper and the web page aren't really similar.

I don't know - they seem pretty similar to me, in terms of conveying
information etc.
It'd be a better
analogy if the thing representing a value type could be referred to by a
reference type.

Consider, perhaps, instead a library. Books are value types. The card
catalog entries are reference types. You can make copies of the card
catalog easily, and the cards always refer to the same book. But if you
copy a book, you've made a whole new book.

This is inaccurate too, since in reality a single reference doesn't refer
to a value directly, but something that contains a value (either a boxed
value, or a class containing values). But I think it's closer to what's
going on. :)

Hmm... that version doesn't feel quite as close as mine - which is
fairly natural, of course :) The fact that a card is a reference to a
book suggests that the book is actually a reference type, with the
card being the reference itself. That may be what you were saying in
the second paragraph; I'm not sure.

It does show what I said earlier - actually *teaching* the concept is
a good deal harder than merely *learning* it! The experience I had
personally, and one which others have since agreed with, is that
there's a bit of a lightbulb moment where everything suddenly makes
sense.

I suspect that it would take a *remarkably* good piece of writing to
make the lightbulb moment occur for most people reading it for the
first time. It seems more likely to me that the teaching material (of
whatever form) will set the student down a subconscious train of
thought, and they'll get the lightbulb moment later. The best we can
hope for is to set the train in the right direction and not put any
obstacles in its way.

It's a lot easier to do this in an interactive context, of course,
with questions and answers. Whiteboards are particularly helpful :)
I very much agree with that. One way or the other, it's important to
teach the fundamentals correctly the first time. Using wrong descriptions
of what's going on can never help with simpler implementations, and it
always leads to incorrect implementations in more complicated scenarios
(how many times have we seen someone passing a class reference by
reference, because they thought that was more efficient than passing the
reference by value?)

Absolutely. Likewise, how many times have we heard people referring to
structs as "lightweight classes" or stating that structs are on the
stack and classes are on the heap. All of these slightly distorted
views on reality are much simpler to clarify with the right mental
model to start with.

Jon
 
J

Jon Skeet [C# MVP]

Yup, still can't disagree with you. That's why I made some changes.

Take a look and drop me an email if you like. Won't post the address here
for obvious spammy reasons but drop me a line on the contact form by all
means.

Will have a look tonight. Happy to have a look at your other pages
too, if you'd like - in particular I noticed (on a quick skim a while
ago) talk about "event objects" in your description of events; I had
no idea what you were talking about at that point.

Jon
 
B

BlackWasp

Found that reference to event object.

I guess it is a terminology thing (unless I found a differrent reference to
event object). I learned a lot of C# from Herb Schildt's writings and have
stuck with the same terminology (the Law of Primacy again!).

Anyhoo, as I said, feel free to drop me an email - this thread is getting
way too long!

Cheers

--

BlackWasp
www.blackwasp.co.uk
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top