Method overloading allows the author of the class to create a method with varying (number and/or type of) parameters, rather than having to have many methods with similar but different names.
The signature of a method is its name and its parameter list.
Properties are public accessors to your encapsulated data. Properties appear to the class creator as methods, but to the class’s clients as fields.
Do not implement the set
part of the property. No special
notation is required.
By passing in parameters by reference and getting the results back in those parameters.
If you want to pass a value object (variable) by
reference, you can use the keyword ref
in the call to the method and in
the declaration of the method.
If you want to pass a value object by reference, but do
not want to initialize it, you must use the keyword out
in the call to the method and in
the declaration of the method.
Write a program with an overloaded method for doubling the
value of the argument. One version of the method should double
an int
value, and the other
version should double a float
value. Call both methods to demonstrate that they work.
using System; namespace InsideMethods { class Tester { public void Run( ) { int x = 5; float y = 5.2f; Console.WriteLine( "Double {0} = {1}", x, Doubler( x ) ); Console.WriteLine( "Double {0} = {1}", y, Doubler( y ) ); } static int Doubler( int theVal ) { return theVal * 2; } static float Doubler( float theVal ) { return theVal * 2.0f; } static void Main( ) { Tester t = new Tester( ); t.Run( ); } } }
Write a program with one method that takes an int
value, and returns both double and
triple that value. You’ll need to use reference
parameters.
using System; namespace InsideMethods { class Tester { public void Run( ) { int x = 5; int doubleX = 0; int tripleX =0; DoublerAndTripler( x, ref doubleX, ref tripleX ); Console.WriteLine( "Double {0} = {1}; triple {2} = {3}", x, doubleX, x, tripleX ); } static void DoublerAndTripler( int theVal, ref int doubleValue, ref int tripleValue ) { doubleValue = theVal * 2; tripleValue = theVal * 3; } static void Main( ) { Tester t = new Tester( ); t.Run( ); } } }
Modify the program from Exercise 8-2 so that you don’t need to initialize the variables that will hold the doubled and tripled values before calling the method:
using System; namespace InsideMethods { class Tester { public void Run( ) { int x = 5; int doubleX; // uninitialized int tripleX; // uninitialized DoublerAndTripler( x, out doubleX, out tripleX ); Console.WriteLine( "Double {0} = {1}; triple {2} = {3}", x, doubleX, x, tripleX ); } static void DoublerAndTripler( int theVal, out int doubleValue, out int tripleValue ) { doubleValue = theVal * 2; tripleValue = theVal * 3; } static void Main( ) { Tester t = new Tester( ); t.Run( ); } } }