Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Output of the following code is: delegate int NumberChanger(int n); namespace

ID: 3854976 • Letter: 1

Question

1. Output of the following code is:

delegate int NumberChanger(int n);

namespace DelegateApp

{

   class TestDelegate

   {

      static int num = 10;

      public static int AddNum(int p)

      {

         num += p;

         return num;

      }

      public static int MultNum(int q)

      {

         num *= q;

         return num;

      }

      static void Main(string[] args)

      {

         //create delegate instances

         NumberChanger nc;

         NumberChanger nc1 = new NumberChanger(AddNum);

         NumberChanger nc2 = new NumberChanger(MultNum);

         nc = nc1;

         nc = nc2;

        

         //Invoke

num = nc(5);

         Console.WriteLine("Value of Num: {0}", num);

         Console.ReadKey();

      }

   }

}

2. What modifier should be used with a method if you have a class which can be used directly, but for which you want inheritors to be able to change certain behavior.

3. When you create an abstract method, you provide __________.

4. Abstract classes and interfaces are similar in that __________.

5. When you create any derived class object, __________.

6. In a program that declares a derived class object, you __________ assign it to a variable of its base class type.

Value of Num: 55

Explanation / Answer

1. Value of Num: 50
This program just depicts use of delegates in c#, delegate is nothing but a reference type variable that holds the reference to a method.

2. virtual
When it is up to the inheritos to change, then virtual keyword should be used. Let's say we have a class that has a virtual method, you can override it and provide your own logic with your own implementation.

3. the keyword abstract
Just the keyword is used to create an abstract method, it doesn't include any curly braces or statements.

4. you cannot instantiate concrete objects from either one
If you go on to see the definiton of abstract class, it says one from which you cannot create any concrete instantiations, but from which you can inherit and interfaces also can't instantiate concrete objects.

5. the base class constructor must execute first, then the derived class constructor executes
The base class constructors are always called from the derevied class contructors. Whenever you create derived class object, first base class constructor is called upon and then derived class constructor is executed.

6. can
However, the opposite is not true. Let's say you have Parent class as base and Child class as derived. If you try to do this:
Parent P = new Child(); --> valid
but
Child c = new Parent();
will give you the following error, "Cannot implicitly convert type"

Do comment for further doubts and dont forget to upvote :)