Question

In: Computer Science

C# Discussion questions. Describe the major reasons to create a method. Explain the reason for using...

C# Discussion questions.

  • Describe the major reasons to create a method.
  • Explain the reason for using fully qualified method names
  • Define the scope of a variable
  • Explain how to pass multidimensional and jagged arrays as parameters.
  • What do you think are the advantages of using methods in your programs? Is it possible to write a complete large-scale program without methods?
  • What is the difference between reference parameters and output parameters? When should you use each?

Solutions

Expert Solution

Describe the major reasons to create a method.

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method.Methods are used to perform certain actions, and they are also known as functions.In c#, Method is a separate code block and that contains a series of statements to perform particular operations and methods must be declared either in class or struct by specifying the required parameters.Generally, in c# Methods are useful to improve the code reusability by reducing the code duplication.

The major reasons to create a method is

  • To reuse code:define the code once, and use it many times.

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Explain the reason for using fully qualified method names

Inside a namespace, no two classes can have the same name. In C#, the full name of the class starts from its namespace name followed by dot(.) operator and the class name, which is termed as the fully qualified name of the class.

Namespaces are only really useful for a few reasons:

  1. Helping to distinguish between classes with the same name
  2. To help 'structure' the project into meaningful pieces

As Oded mentioned, these reasons alone can be very important - although uncommon, ambiguity is not impossible and in this case using namespaces would be a necessity.

Defining a Namespace

A namespace definition begins with the keyword namespace followed by the namespace name as follows −

namespace namespace_name {
   // code declarations
}

To call the namespace-enabled version of either function or variable, prepend the namespace name as follows −

namespace_name.item_name;

The following program demonstrates use of namespaces −

Live Demo

using System;

namespace first_space {
   class namespace_cl {
      public void func() {
         Console.WriteLine("Inside first_space");
      }
   }
}
namespace second_space {
   class namespace_cl {
      public void func() {
         Console.WriteLine("Inside second_space");
      }
   }
}
class TestClass {
   static void Main(string[] args) {
      first_space.namespace_cl fc = new first_space.namespace_cl();
      second_space.namespace_cl sc = new second_space.namespace_cl();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

When the above code is compiled and executed, it produces the following result −

Inside first_space
Inside second_space

The using Keyword

The using keyword states that the program is using the names in the given namespace. For example, we are using the System namespace in our programs. The class Console is defined there. We just write −

Console.WriteLine ("Hello there");

We could have written the fully qualified name as −

System.Console.WriteLine("Hello there");

You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code −

Let us rewrite our preceding example, with using directive −

Live Demo

using System;
using first_space;
using second_space;

namespace first_space {
   class abc {
      public void func() {
         Console.WriteLine("Inside first_space");
      }
   }
}
namespace second_space {
   class efg {
      public void func() {
         Console.WriteLine("Inside second_space");
      }
   }
}   
class TestClass {
   static void Main(string[] args) {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

When the above code is compiled and executed, it produces the following result −

Inside first_space
Inside second_space

Nested Namespaces

You can define one namespace inside another namespace as follows −

namespace namespace_name1 {
   
   // code declarations
   namespace namespace_name2 {
      // code declarations
   }
}

You can access members of nested namespace by using the dot (.) operator as follows −

Live Demo

using System;
using first_space;
using first_space.second_space;

namespace first_space {
   class abc {
      public void func() {
         Console.WriteLine("Inside first_space");
      }
   }
   namespace second_space {
      class efg {
         public void func() {
            Console.WriteLine("Inside second_space");
         }
      }
   }   
}
class TestClass {
   static void Main(string[] args) {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

When the above code is compiled and executed, it produces the following result −

Inside first_space
Inside second_space

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Define the scope of a variable

The scope of a variable determines its visibility to the rest of a program. In the examples throughout the C# Fundamentals tutorial, variables have been defined within methods. When created in this way, the scope of the variable is the entire method after the declaration. This means that the variable is available to use within the method but when control passes to another method the variable is unavailable.

There are other possibilities for a variable's scope. For example, a variable can be declared within a loop or other code structure and be only visible to the code within the structure. A wider scoped variable could be declared at class-level so that it can be used by any method within the class. In fact, a variable's scope is always the full extent of the code block it is declared within.

As has been demonstrated throughout the tutorial, code blocks can be nested. A loop within a method within a class provides three levels of nested code blocks and, therefore, three levels of nested scope. When a variable is declared within one of these nested scopes, it is visible only to the current scope and any scopes nested within it. This means that a variable declared within a loop is not visible outside of that loop whereas a variable declared outside of the loop is also visible within the loop.

Class-Level Scope

Variables that are defined at the class level are available to any non-static method within the class. In this article the full extent of class scopes is not discussed as the object-oriented programming techniques involved are beyond the scope of a beginner's tutorial.

Method-Level Scope

Variables declared within a method's code block are available for use by any other part of the method, including nested code blocks. The following example demonstrates this by creating a variable in the method, setting its value and then using it within the scope of an 'if' statement.

static void Main(string[] args)

{

    int score;                                          // Declared at method-level

    score = 100;                                        // Used at method-level

    if (score >= 50)

        Console.WriteLine("Good score : {0}", score);   // Used in nested scope

    else

        Console.WriteLine("Poor score : {0}", score);   // Used in nested scope

}

Nested Scope

As described earlier in the article, variables declared within a nested scope are not available to those outside of their code block. The following code will not compile because the variable that is attempted to be used at method level is declared in the more deeply nested scope of the if statement.

static void Main(string[] args)

{

    int score = 100;

    if (score >= 50)

        string message = "Good score";                  // Declared in if statement

    else

        string message = "Poor score";                  // Declared in if statement

    Console.WriteLine(message);                         // Variable unavailable

}

NB: To make this example work, the variable would be declared before the if statement and simply assigned a value within the if statement.

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Explain how to pass multidimensional and jagged arrays as parameters.

Jagged array is a array of arrays such that member arrays can be of different sizes. In other words, the length of each array index can differ. The elements of Jagged Array are reference types and initialized to null by default. Jagged Array can also be mixed with multidimensional arrays. Here, the number of rows will be fixed at the declaration time, but you can vary the number of columns.

Declaration

In Jagged arrays, user has to provide the number of rows only. If the user is also going to provide the number of columns, then this array will be no more Jagged Array.

Syntax:

data_type[][] name_of_array = new data_type[rows][]

Example:

int[][] jagged_arr = new int[4][]

In the above example, a single-dimensional array is declared that has 4 elements(rows), each of which is a 1-D array of integers.

Passing Multidimensional Array to Method

We can also pass a multidimensional array to a method. For example, to pass a 2D array of integers to a method Abc, we will write - Abc(int[,] a).

Let's look at an example.

using System;

class Test
{
  static void Display(int[,] a)
  {
    foreach(int i in a)
      Console.Write($"{i}\t");
    Console.Write("\n");
  }
  static void Main(string[] args)
  {
    int[,] a = new int[2, 2];
    a[0, 0] = 1;
    a[0, 1] = 2;
    a[1, 0] = 3;
    a[1, 1] = 4;

    int[,] b = new int[2, 2] { {5, 6}, {7, 8} };

    int[,] c = {
      {9, 10},
      {11, 12}
    };

    Display(a);
    Display(b);
    Display(c);
  }
}

Output

1  2  3  4
5  6  7  8
9  10  11  12

Here, the Display method is taking a 2D array of integers - Display(int[,] a).

Similarly, we can have 3D array as:

int[, ,] a = new int[5,6,7];

4D array as

int[, , ,] a = new int[5,6,7,3];

and so on.

Returning Multidimensional Array from Method

To return a 2D array from a method, we will specify its return type as [,]. For example, to return a 2D array from a function Abc, we would specify - int[,] Abc().

Let's look at an example.

using System;

class Test
{
  static int[,] MultiReturn()
  {
    int[,] a = new int[2, 2] { {5, 6}, {7, 8} };
    return a;
  }
  static void Main(string[] args)
  {
    int[,] a = MultiReturn();

    foreach(int i in a)
      Console.Write($"{i}\t");
    Console.Write("\n");
  }
}

Output

5  6  7  8

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

What do you think are the advantages of using methods in your programs?

Advantages of using the Methods :

  • It makes the program well structured.
  • Methods enhance the readability of the code.
  • It provides an effective way for the user to reuse the existing code.
  • It optimizes the execution time and memory space.

Is it possible to write a complete large-scale program without methods?

Yes, it is possible write a complete large scale program without method but the applications that run on distributed systems are much more complicated to design than corresponding applications that run on more centralized systems, such as a mainframe computer. Distributed systems must tolerate the failure of one or more component computers without compromising any critical application data or consistency, and preferably without crashing the system. The designs, algorithms, and programming techniques required to build high-quality distributed systems are much more complex than those for older, more conventional applications.

Large-scale IT systems are notoriously difficult to design, develop, and operate reliably. The list of problematic system development efforts is long and growing . In some cases, difficulties in design and development have resulted in significant cost overruns and/or a lack of desired functionality in fielded systems. In others, major IT systems were cancelled before they were ever fielded because of problems in development.

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

What is the difference between reference parameters and output parameters? When should you use each?

REFERENCE PARAMETERS

  • It is necessary the parameters should initialize before it pass to ref
  • It is not necessary to initialize the value of a parameter before returning to the calling method.
  • The passing of value through ref parameter is useful when the called method also need to change the value of passed parameter.
  • When ref keyword is used the data may pass in bi-directional.

uses

The ref keyword indicates a value that is passed by reference. It is used in four different contexts:

  • In a method signature and in a method call, to pass an argument to a method by reference.
  • In a method signature, to return a value to the caller by reference.
  • In a member body, to indicate that a reference return value is stored locally as a reference that the caller intends to modify or, in general, a local variable accesses another value by reference.
  • In a struct declaration to declare a ref struct or a readonly ref struct.

OUTPUT PARAMETERS

  • It is not necessary to initialize parameters before it pass to out.
  • It is necessary to initialize the value of a parameter before returning to the calling method.
  • The declaring of parameter through out parameter is useful when a method return multiple values.
  • When out keyword is used the data only passed in unidirectional.

USES

The out keyword causes arguments to be passed by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. It is like the ref keyword, except that ref requires that the variable be initialized before it is passed. It is also like the in keyword, except that in does not allow the called method to modify the argument value. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

PLEASE DON'T FORGET TO UPVOTE.

THANKYOU.


Related Solutions

) Write the major reasons for using admixtures for modifications fresh concrete?
) Write the major reasons for using admixtures for modifications fresh concrete?
Describe the reason why the scientific method is the basis for scientific discovery and the role...
Describe the reason why the scientific method is the basis for scientific discovery and the role that it plays in creating sound and reliable theories. ***Note, this is an extended essay question, worth 40 points. The response should be formatted in multi-paragraph essay with attention to essay structure, grammar mechanics, and APA formatting.***
The following questions can be answered using the scientific method? Explain a. Could the concentration of...
The following questions can be answered using the scientific method? Explain a. Could the concentration of salt in the Cabo Rojo Salt Flats inhibit the growth of algae? b. Is the horoscope a reliable way of knowing what will happen to us the next day?
JAVA: *USING INHERITANCE *USING SUPER IN TH CONSTRUCTOR *USING SUPER IN THE METHOD *METHOD OVERRIDING Create...
JAVA: *USING INHERITANCE *USING SUPER IN TH CONSTRUCTOR *USING SUPER IN THE METHOD *METHOD OVERRIDING Create an application with 5 classes: 1.) Vehicle 2.) Car 3.) Bus 4.) Truck 5.) Tester Following characteristics should be used: make, weight, height, length, maxSpeed, numberDoors, maxPassengers, isCpnvertable, numberSeats, maxWeightLoad, numberAxels **Class Vehicle: should have a constructor that initializes all of it's data **Classes Car, Bus, Truck: will have constructors that resuse their parents constructors and provide additional code for initalizing their specific data...
1) Explain the mechanism of DPSK, and the reason of using DPSK.
1) Explain the mechanism of DPSK, and the reason of using DPSK.
1. What are the reasons for international capital markets? Explain each reason. 2. What is an...
1. What are the reasons for international capital markets? Explain each reason. 2. What is an offshore center? Why do you think that attracts a lot of business activities?
List and explain some of other major reasons for economic plan failure in Pakistan. Which reasons...
List and explain some of other major reasons for economic plan failure in Pakistan. Which reasons do you think are the most important and why?
Case Study on Walmart using IT A major reason for Wal-Mart’s success over the year was...
Case Study on Walmart using IT A major reason for Wal-Mart’s success over the year was its constant emphasis on installing the most modern IT systems, which helped it achieve better economy of scale, distribution efficiency and pass on the benefits of the same to the customers. By offering low price to customers, Wal-Mart was able to generate more sales and minimize the promotional expenditure of the company. By using IT, Wal-Mart was able to establish proper communication links with...
Case Study on Walmart using IT A major reason for Wal-Mart’s success over the year was...
Case Study on Walmart using IT A major reason for Wal-Mart’s success over the year was its constant emphasis on installing the most modern IT systems, which helped it achieve better economy of scale, distribution efficiency and pass on the benefits of the same to the customers. By offering low price to customers, Wal-Mart was able to generate more sales and minimize the promotional expenditure of the company. By using IT, Wal-Mart was able to establish proper communication links with...
Using C# Create a class named Inches To Feet. Its Main()method holds an integer variable named...
Using C# Create a class named Inches To Feet. Its Main()method holds an integer variable named inches to which you will assign a value. Create a method to which you pass inches. The method displays inches in feet and inches. For example, 67 inches is 5 feet 7 inches.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT