Home

The Members of the Main Class

 

Introduction to Members

 

Introduction to Methods

One of the purposes of writing a program is to perform assignments. An assignment can also be called a function. The C# doesn't have the same notion of a function as did traditional and previous languages like C/C++, Pascal, etc. Instead, in C#, a function must belong to a class. Therefore, in C#, a function is a section whose job is to take care of an operation that would complement a class. Because a function in this case belongs to a particular class, the function is also called a method. From now on, the name method will be used for a function.

Author Note   C++ Note

In C++, a function can be declared anywhere, making it distinct from a method. In C#, a function can be declared only inside of, or as a member of, a class

Like everything else, a method must have a name. We will follow the same rules and conventions we defined for all names. An example of a method's name would be Welcome. To distinguish a method from a variable, it is always followed by parentheses, sometimes empty. Since a method is used to perform an assignment, its job is included between an opening curly bracket "{" and a closing curly bracket "}". Here is an example:

using System;

class Exercise
{
	Welcome() { }

	static void Main()
	{
		Console.WriteLine();
	}
}

If the assignment performed by a method is long, you can use many lines to define its behavior. For this reason, each bracket can be typed on its own line.

After a method has performed its assignment, it may provide a result. The result of a method is called a return value. Each return value follows a particular type based on one of the data types we reviewed on variables. Any time you create a method, the compiler needs to know the type of value that the method would return. The type of value that a method would return is specified on the left side of the method's name.

Some, even many, of the methods used in your programs will not return a value after they have performed an assignment. When a method doesn't return a value, it is considered void. The return type of such a method is the void keyword. Here is an example:

using System;

class Exercise
{
	void Welcome()
	{
	}

	static void Main()
	{
		Console.WriteLine();
	}
}

In the exercises of this lesson, we will perform calculations for a cylinder with circular base:

Figure Areas Volume
Cylinder
Base Area = R * R * Pi
Lateral Area = 2 * Pi * R * H
Total Area = 2PiRH + 2PiR2     
 
PiR2H

 

Practical Learning Practical Learning: Introducing Global Members

  1. Start Microsoft Visual C# or Visual Studio .NET
  2. On the main menu, click File -> New -> Project
  3. If necessary, in the Project Types list of the New Project dialog box, click Visual C# Projects
  4. In the Templates list, click Empty Project
  5. In the Name text box, replace the name with Geometry1 and specify the desired path in the Location
  6. Click OK
  7. To create a source file for the project, on the main menu, click Project -> Add New Item...
  8. In the Add New Item dialog box, in the Templates list, click Code File
  9. In the Name text box, delete the suggested name and replace it with Exercise
  10. Click Open
  11. In the empty file, type the following:
     
    using System;
    
    namespace GeometricFormulas
    {
    	class Cylinder
    	{
    		static void Main()
    		{
    			Console.WriteLine();
    		}
    	}
    }
  12. Save the file
 

Static Methods

Unlike some other languages like C/C++, Pascal, Visual Basic, etc, but like Java, C# doesn't have the notion of global function: every method must belong to a class. For this reason, every program uses at least one class and we call this primary class, the main class. Because of this feature of the language, it imposes some rules on the way methods can be called. If you create a method in the main class of your project, you should indicate that the method will always belong to this main class. The method must be created as static.

To define a method as static, type the static keyword to its left. Here is an example:

using System;

class Exercise
{
	static void Welcome()
	{
	}

	static void Main()
	{
		Console.WriteLine();
	}
}

As we have used the Main() function so far, the behavior of a method is defined between its delimiting curly brackets. The section inside the curly brackets is called the body of a method. In the body of the method, you can simply display a sentence. Here is an example:

using System;

class Exercise
{
	static void Welcome()
	{
		Console.WriteLine("Welcome to the Wonderful World of C#");
	}

	static void Main()
	{
		Console.WriteLine();
	}
}

In the same way, you can use a method to perform any other assignment. After creating a method, you can use it where needed. Using a method is also referred to as calling it. If you create a simple method like the above Welcome(), to call it, type its name followed by parentheses and ending with a semi-colon. Here is an example:

using System;

class Exercise
{
	static void Welcome()
	{
		Console.WriteLine("Welcome to the Wonderful World of C#");
	}

	static void Main()
	{
		Welcome();

		Console.WriteLine();
	}
}

Practical Learning Practical Learning: Creating a Static Method

  1. To define a static method, change the file as follows:
     
    using System;
    
    class Cylinder
    {
    	static void ProcessCylinder()
    	{
    		Console.WriteLine("Cylinder Characteristics");
    	}
    
    	static void Main()
    	{
    		ProcessCylinder();
    
    		Console.WriteLine();
    	}
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. Return to Visual C#

Local Variables

In the body of a method, you can also declare variables that would be used internally. A variable declared in the body is referred to as a local variable. It cannot be accessed outside of the method it belongs to. After declaring a local variable, it is made available to the method and you can use it as you see fit, for example, you can assign it a value prior to using it.

Practical Learning Practical Learning: Using a Method's Local Variables

  1. To declare and use local variables of a method, change the static method as follows:
     
    using System;
    
    namespace GeometricFormulas
    {
    	class Cylinder
    	{
    		static void ProcessCylinder()
    		{
    			double Radius, Height;
    			double BaseArea, LateralArea, TotalArea;
    			double Volume;
    
    			Console.WriteLine("Enter the dimensions of the cylinder");
    			Console.Write("Radius: ");
    			Radius = double.Parse(Console.ReadLine());
    			Console.Write("Height: ");
    			Height = double.Parse(Console.ReadLine());
    
    			BaseArea    = Radius * Radius * Math.PI;
    			LateralArea = 2 * Math.PI * Radius * Height;
    			TotalArea   = 2 * Math.PI * Radius * (Height + Radius);
    			Volume      = Math.PI * Radius * Radius * Height;
    
    			Console.WriteLine("\nCylinder Characteristics");
    			Console.WriteLine("Radius:  {0}", Radius);
    			Console.WriteLine("Height:  {0}", Height);
    			Console.WriteLine("Base:    {0:F}", BaseArea);
    			Console.WriteLine("Lateral: {0:F}", LateralArea);
    			Console.WriteLine("Total:   {0:F}", TotalArea);
    			Console.WriteLine("Volume:  {0:F}", Volume);
    		}
    
    		static void Main()
    		{
    			ProcessCylinder();
    
    			Console.WriteLine();
    		}
    	}
    }
  2. Execute the application. Here is an example:
     
    Enter the dimensions of the cylinder
    Radius: 38.64
    Height: 22.48
    
    Cylinder Characteristics
    Radius:  38.64
    Height:  22.48
    Base:    4690.55
    Lateral: 5457.75
    Total:   14838.85
    Volume:  105443.65
  3. Return to Visual C#
 

A Method that Returns a Value 

If a method has carried an assignment and must make its result available to other methods or other classes, the method must return a value and cannot be void. To declare a method that returns a value, provide its return type to the left of its name. Here is an example:

using System;

class Exercise
{
	static double Operation()
	{
	}

	static void Main()
	{
	}
}

After a method has performed its assignment, it must clearly demonstrate that it is returning a value. To do this, you use the return keyword followed by the value that the method is returning. The value returned must be of the same type specified as the return type of the method. Here is an example:

using System;

class Exercise
{
	static double Operation()
	{
		return 24.55;
	}

	static void Main()
	{
	}
}

A method can also return an expression, provided the expression produces a value that is conform to the return type. Here is an example:

using System;

class Exercise
{
	static double Operation()
	{
		return 24.55 * 4.16;
	}

	static void Main()
	{
	}
}

When a method returns a value, the compiler considers such a method as if it were a regular value. This means that you can use Console.Write() or Console.WriteLine() to display its value. To do this, simply type the name of the method and its parentheses in the Console.Write() of the Console.WriteLine() methods' parentheses. Here is an example:

using System;

class Exercise
{
	static double Operation()
	{
		return 24.55;
	}

	static void Main()
	{
		Console.WriteLine(Operation());
	}
}

In the same way, a method returns a value can be assigned to a variable of the same type.

Practical Learning Practical Learning: Returning a Value From a Method 

  1. To create methods that return values, change the program as follows:
     
    using System;
    
    namespace GeometricFormulas
    {
    	class Cylinder
    	{
    		static double GetRadius()
    		{
    			double rad;
    
    			Console.Write("Radius: ");
    			rad = double.Parse(Console.ReadLine());
    
    			return rad;
    		}
    
    		static double GetHeight()
    		{
    			double h;
    
    			Console.Write("Height: ");
    			h = double.Parse(Console.ReadLine());
    
    			return h;
    		}
    
    		static void ProcessCylinder()
    		{
    			double Radius, Height;
    			double BaseArea, LateralArea, TotalArea;
    			double Volume;
    
    			Console.WriteLine("Enter the dimensions of the cylinder");
    			Radius = GetRadius();
    			Height = GetHeight();
    
    			BaseArea    = Radius * Radius * Math.PI;
    			LateralArea = 2 * Math.PI * Radius * Height;
    			TotalArea   = 2 * Math.PI * Radius * (Height + Radius);
    			Volume      = Math.PI * Radius * Radius * Height;
    
    			Console.WriteLine("\nCylinder Characteristics");
    			Console.WriteLine("Radius:  {0}", Radius);
    			Console.WriteLine("Height:  {0}", Height);
    			Console.WriteLine("Base:    {0:F}", BaseArea);
    			Console.WriteLine("Lateral: {0:F}", LateralArea);
    			Console.WriteLine("Total:   {0:F}", TotalArea);
    			Console.WriteLine("Volume:  {0:F}", Volume);
    		}
    
    		static void Main()
    		{
    			ProcessCylinder();
    
    			Console.WriteLine();
    		}
    	}
    }
  2. Save, compile, and test the file. Here is an example of running the program:
     
    Enter the dimensions of the cylinder
    Radius: 52.08
    Height: 36.44
    
    Cylinder Characteristics
    Radius:  52.08
    Height:  36.44
    Base:    8521.02
    Lateral: 11924.20
    Total:   28966.25
    Volume:  310506.14
  3. Return to Visual C#

Pseudo-Global Variables

As mentioned with functions, C# doesn't have the notion of global variables (in C/C++, Visual Basic, Pascal, etc, a global variable is one that is declared outside of any class; such a variable is made available to any function, or even file, of the same program without being declared again where needed). Still, if you want to use the same variable in various methods of the main class, you can declare it outside of any method. The variable must be declared as static. That is, you must type the static keyword to its left when declaring it. Here is an example:

using System;

class Exercise
{
	static double Length;

	static void Welcome()
	{
		Console.WriteLine("Welcome to the Wonderful World of C#");
	}

	static void Main()
	{
		Welcome();

		Console.WriteLine();
	}
}

After declaring such a variable, you can access from any method that belongs to the same class.

 

Practical Learning Practical Learning: Using Global Variables 

  1. To declare and use global variables, change the file as follows:
     
    using System;
    
    namespace GeometricFormulas
    {
    	class Cylinder
    	{
    		static double Radius;
    		static double Height;
    		static double BaseArea;
    		static double LateralArea;
    		static double TotalArea;
    		static double Volume;
    
    		static double GetRadius()
    		{
    			double rad;
    
    			Console.Write("Radius: ");
    			rad = double.Parse(Console.ReadLine());
    
    			return rad;
    		}
    
    		static double GetHeight()
    		{
    			double h;
    
    			Console.Write("Height: ");
    			h = double.Parse(Console.ReadLine());
    
    			return h;
    		}
    
    		static void ProcessCylinder()
    		{
    			Console.WriteLine("Enter the dimensions of the cylinder");
    			Radius = GetRadius();
    			Height = GetHeight();
    
    			BaseArea    = Radius * Radius * Math.PI;
    			LateralArea = 2 * Math.PI * Radius * Height;
    			TotalArea   = 2 * Math.PI * Radius * (Height + Radius);
    			Volume      = Math.PI * Radius * Radius * Height;
    		}
    
    		static void ShowCylinder()
    		{
    			Console.WriteLine("\nCylinder Characteristics");
    			Console.WriteLine("Radius:  {0}", Radius);
    			Console.WriteLine("Height:  {0}", Height);
    			Console.WriteLine("Base:    {0:F}", BaseArea);
    			Console.WriteLine("Lateral: {0:F}", LateralArea);
    			Console.WriteLine("Total:   {0:F}", TotalArea);
    			Console.WriteLine("Volume:  {0:F}", Volume);
    		}
    
    		static void Main()
    		{
    			ProcessCylinder();
    			ShowCylinder();
    
    			Console.WriteLine();
    		}
    	}
    }
  2. Save, compile, and test the file. Here is an example of running the program:
     
    Enter the dimensions of the cylinder
    Radius: 38.24
    Height: 32.58
    
    Cylinder Characteristics
    Radius:  38.24
    Height:  32.58
    Base:    4593.94
    Lateral: 7827.96
    Total:   17015.85
    Volume:  149670.68
  3. Return to Notepad

Methods and Conditional Statements

 

Using Conditions in Functions

The use of methods in a program allows you to isolate assignments and confine them to appropriate entities. While the methods take care of specific requests, you can provide them with conditional statements to validate what these methods do. There are no set rules to the techniques involved. Everything depends on the tasks at hand. To make effective use of methods, you should be very familiar with different data types because you will need to return the right value.

Suppose you write an ergonomic program that needs to check different things including answers from the user in order to proceed. These various assignments can be given to methods that would simply hand the results to the Main() function that can, in turn, send these results to other functions for further processing. Here is an example:

using System;

public class NewProject
{
	static char GetPosition()
	{
		char Position;
		string Pos;

		do {
			Console.Write("Are you sitting down now(y/n)? ");
			Pos = Console.ReadLine();;
            		Position = char.Parse(Pos);

			if( Position != 'y' && Position != 'Y' &&
                		Position != 'n' && Position != 'N' )
				Console.WriteLine("Invalid Answer\n");
		} while( Position != 'y' && Position != 'Y' &&
				 Position != 'n' && Position != 'N' );

		return Position;
	}

	static void Main()
	{
		char Position;

		Position = GetPosition();
	
		if( Position == 'n' || Position == 'N' )
			Console.WriteLine("\nCould you please sit down for the next exercise?\n");
		else
			Console.WriteLine("\nWonderful!!!\n\n"); 
	}
}

Here is an example of running the program:

Are you sitting down now(y/n)? V
Invalid Answer

Are you sitting down now(y/n)? z
Invalid Answer

Are you sitting down now(y/n)? n

Could you please sit down for the next exercise?

Methods don't have to return a value in order to be involved with conditional statements. In fact, both issues are fairly independent. This means that, void and non-void methods can manipulate values based on conditions internal to them.

 

Practical Learning Practical Learning: Using Conditional Statements With Methods

  1. To include conditional statements in your methods, change the file as follows:
     
    using System;
    
    namespace GeometricFormulas
    {
    	class Cylinder
    	{
    		static double Radius;
    		static double Height;
    		static double BaseArea;
    		static double LateralArea;
    		static double TotalArea;
    		static double Volume;
    
    		static double GetRadius()
    		{
    			double rad;
    
    			do 
    			{
    				Console.Write("Radius: ");
    				rad = double.Parse(Console.ReadLine());
    				if( rad < 0 )
    					Console.WriteLine("Please enter a positive number");
    			} while( rad < 0 );
    
    			return rad;
    		}
    
    		static double GetHeight()
    		{
    			double h;
    
    			do 
    			{
    				Console.Write("Height: ");
    				h = double.Parse(Console.ReadLine());
    				if( h < 0 )
    					Console.WriteLine("Please enter a positive number");
    			} while( h < 0 );
    
    			return h;
    		}
    
    		static void ProcessCylinder()
    		{
    			Console.WriteLine("Enter the dimensions of the cylinder");
    			Radius = GetRadius();
    			Height = GetHeight();
    
    			BaseArea    = Radius * Radius * Math.PI;
    			LateralArea = 2 * Math.PI * Radius * Height;
    			TotalArea   = 2 * Math.PI * Radius * (Height + Radius);
    			Volume      = Math.PI * Radius * Radius * Height;
    		}
    
    		static void ShowCylinder()
    		{
    			Console.WriteLine("\nCylinder Characteristics");
    			Console.WriteLine("Radius:  {0}", Radius);
    			Console.WriteLine("Height:  {0}", Height);
    			Console.WriteLine("Base:    {0:F}", BaseArea);
    			Console.WriteLine("Lateral: {0:F}", LateralArea);
    			Console.WriteLine("Total:   {0:F}", TotalArea);
    			Console.WriteLine("Volume:  {0:F}", Volume);
    		}
    
    		static void Main()
    		{
    			ProcessCylinder();
    			ShowCylinder();
    
    			Console.WriteLine();
    		}
    	}
    }
  2. Save, compile, and test the file. Here is an example of running the program:
     
    Enter the dimensions of the cylinder
    Radius: -24.55
    Please enter a positive number
    Radius: 24.55
    Height: -18
    Please enter a positive number
    Height: 18.75
    
    Cylinder Characteristics
    Radius:  24.55
    Height:  18.75
    Base:    1893.45
    Lateral: 2892.23
    Total:   6679.12
    Volume:  35502.11
  3. Return to Notepad

Conditional Returns

A method defined other than void must always return a value. Sometimes, a method will perform some tasks whose results would lead to different results. A method can return only one value (this is true for this context, but there are ways to pass arguments so that a method can return more than one value) but you can make it render a result depending on a particular behavior. If a method is requesting an answer from the user, since the user can provide different answers, you can treat each result differently.

Imagine you write the following method:

using System;

public class NewProject
{
	static string GetPosition()
	{
		char Position;
	
		Console.Write("Are you sitting down now(y/n)? ");
		string Pos = Console.ReadLine();
		Position = char.Parse(Pos);
	
		if( Position == 'y' || Position == 'Y' )
			return "Yes";
		else if( Position == 'n' || Position == 'N' )
			return "No";
	}

	static void Main()
	{
		string Answer;
	
		Answer = GetPosition();
		Console.Write("\nAnswer = ");
		Console.WriteLine(Answer);
	}
}

When running this program, you would receive an error. On paper, the function looks fine. If the user answers with y or Y, the function returns the string Yes. If the user answer with n or N, the function returns the string No. Unfortunately, this function has a problem: what if there is an answer that does not fit those we are expecting? The values that we have returned in the function conform only to the conditional statements and not to the function. Remember that in if(Condidion)Statement, the Statement executes only if the Condition is true. Here is what will happen. If the user answers y or Y, the function returns Yes and stops. If the user answers n or N, the function returns No, which also is a valid value. If the user enters another value (other than y, Y, n, or N), the execution of the function will not execute any of the returned statements and will not exit. This means that the execution will reach the closing curly bracket without encountering a return value. This would mean to the compiler that you wrote a non-void method that is supposed to return a value, but by the end of the method, it didn't return a value. That's why the compiler displays an error. The solution is to provide a return value so that, if the execution reaches the end of the function, it would still return something. Here is a solution to the problem:

using System;

public class NewProject
{
	static string GetPosition()
	{
		char Position;
	
		Console.Write("Are you sitting down now(y/n)? ");
		string Pos = Console.ReadLine();
		Position = char.Parse(Pos);
	
		if( Position == 'y' || Position == 'Y' )
			return "Yes";
		else if( Position == 'n' || Position == 'N' )
			return "No";
		return "Invalid Answer";
	}

	static void Main()
	{
		string Answer;
	
		Answer = GetPosition();
		Console.Write("\nAnswer = ");
		Console.WriteLine(Answer);
	}
}

Here is an example of running the program:

Are you sitting down now(y/n)? g

Answer = Invalid Answer

void Methods and Conditional Returns

So far, we have seen that void methods don't return a value. Still, the return keyword can be used in a void method. It allows you to exit a method before the last line if you judge it necessary. Suppose that you ask a question in a method or validate a condition. Once the condition is valid, you may not see any reason to continue further. In this case, you would like to interrupt the flow in that method and continue with the next task in another method.

To get an early exit from a method, where you judge it necessary, type the return keyword followed by a semi-colon. Of course, since this is usually used to value a condition, the return keyword can be typed at the end of a conditional statement.

 

Previous Copyright © 2004-2012, FunctionX Next