Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » C# Methods

C# Methods

This article explains hot to define and use methods in C#.

Total page views :  71036
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

Introduction to C# Methods :

Just in the beginning I like to remind all of you that Computer programs exist to solve a problems and there are methods for solving those problems.

That's how I can explain the meaning of C# methods. All C# programs constructed from a number of classes and those classes contain methods that solve the problems for the program. So a methods is a kind of building blocks that solve a small problem.

For example you have a problem in your program. You need a method to convert a string to integer array for some reason. You can use the following method :

private int[] ToIntArray(string s)
{
int o = s.Length;
int[] iArray = new int[o];
for(int x = 0; x < s.Length; x++)
{
iArray[x] = Convert.ToInt32(s.Substring(x,1));
}
return iArray;
}

So with this method we solve the problem we have here ( if we have a string like "911" this method will convert it to integer array [9,1,1] ). We will not talk about the code written inside the method now but we will focus on introducing you to methods and later we will take a lot of examples. Just note that we use the .NET Framework Class Library (FCL) methods (like ToInt32(), Substring()) inside our methods to create a new methods. That's make our job as a programmers much easier.

When you declare a variable in your method then it's a local variable to that method and no other method can know anything about that variable.

Methods also very useful if you will use a block of code many times in your program so instead of writing the same block of code many times in the program we can put that code in a method and call it whenever we need it to do the job.

How we write C# methods ?

After reading this section you will be able to write methods and understand the concept of (Parameters, Return Value)

We have a line of code and we need to put it inside a method so we understand how we can write C# methods.

Console.WriteLine(Math.Sqrt(9));

This line of code use the Sqrt method of the class Math to get the square root of 9 . We need to create a method to write to the console screen the square root just when we use it (when we call it, Invoke it). Let's take a look at this method :

static void SqrtToConsole(double x)
{
Console.WriteLine(Math.Sqrt(x));
}

to understand this method we need to explain the concept of parameters.

Parameters and parameters value :

A lot of times the method you call will need some information from you to complete its task. For example the ToIntArray() method in the article take one parameter as a string :

private int[] ToIntArray(string s)<--------------- This is called a parameter

So this place where we will put the string into called a parameter. We just tell the method "You have one place (a parameter) where can the user put a value here (a parameter value) and you need this value to finish your task". So when you create the method you specify the parameters that the method will use and when you call it you will specify the parameters value for the parameters. parameters value are the values that you specify for your parameters when you call the function. Every parameters in your method has a data type exactly like variables and you must specify it when you create the method. When you call the method you must specify the parameters value of the same data type or to a type that can be converted to that type. The parameters of any method not accessible outside the method because it's considered as local variables for that method.

Consider the following example :

static void SqrtToConsole(double x)<--------------- This is called a parameter
{
Console.WriteLine(Math.Sqrt(x));
}

We just created a method called SqrtToConsole that take only one parameter. Now we need to call the method ( I mean we need to use the method).

SqrtToConsole(9)<--------------- This is called a parameter value

We called the method SqrtToConsole with 9 as a parameter value for the parameter x.

I think after you understand the concept of Parameters we can explain the code written in the method SqrtToConsole.

static void SqrtToConsole(double x)
{
Console.WriteLine(Math.Sqrt(x));
}

We just created a method called SqrtToConsole with one parameter called x of double data type. We use 2 FCL functions here (WriteLine(),Sqrt()) to complete the task.

The Console.WriteLine() method take one parameter value to write it to the console. Note that the parameter value of this parameter can be an expression . There are 18 overloaded version of Console.WriteLine() method and you can check them in Visual Studio.NET Documentation. Some of them take a parameter value as a string, int, double, object and other data types.

The Math.Sqrt() method take also one parameter value to get its job done. Here we just create our method and inside it we call the Console.WriteLine() with a parameter value as the result of the following method call Math.Sqrt(x).

Note : Don't forget that x is the parameter of the SqrtToConsole() method and we just use it in the Math.Sqrt(x) method so that we tell the compiler to take the parameter value of SqrtToConsole() method and give it to the Math.Sqrt()so the result will write to the console application.

Return Value :

Let's look at the Math.Sqrt() again please. This method takes a parameter of double data type and Returns the square root of that parameter so this is the return value that we are talking about here in C# methods.

Consider the following method :

private int AddIntegers(int x, int y)
{
return x + y ;
}

Here the AddIntegers() method takes 2 integer numbers and return the result as integer too.

The return value must have a type so here in our method the return value is of type int and we must write int keyword before the method name to specify the return type. Also we use the return keyword as the end of our method to exit the method and return the value to the method which called the AddIntegers() ( I will explain how we can call method from other method later ) . So when you use the return keyword you tell the compiler to end the method and return a value of the specified type to the calling code. If your method does not return a value then you must use the void keyword in the same place as you do with the return value type (before the method name).

You must understand something called Method Signature or Method Definition. The group of method name, parameter list, return value type specify the method signature or method definition. For example the method AddIntegers() signature is :

1- The return data type (int)

2- The method name ( AddIntegers )

3- The parameter list ( (int x, int y) )

How we call a method ?

As you might know that the Main method is the entry point of any C# program so it's the first method that the compiler will invoke. So any method we created or any method we used it from FCL will be called from the Main method. Consider the following example :

We have 2 methods as following :

private void Parent()
{
// We don't need any code here
}
private void Son(int x)
{
// We don't need any code here
}

We need to call
this methods from our Main method. All what we need to do like that

static void Main(string[] args)
{
Parent();
Son(23);
}

We called the 2 methods simply by typing the name of the method with 2 empty parenthesis if the method's parameter list is empty or the with parameters values inside the parenthesis if the method's parameter list contains parameters.

Note : a user-defined method can call other methods like another user-defined method or FCL method.

So far I think I have introduced C# methods and in my next article I will talk complete our discussion about methods and introduce some advanced concepts. I hope that you will find my articles useful.


Login to add your contents and source code to this article
 About the author
 
Michael Youssef
Michael Youssef is one of the first few developers around the world who earn Microsoft Certified Solution Developer for Microsoft. NET (MCSD.NET) Certification and also he is Microsoft Certified Database Administrator (MCDBA), Microsoft Certified Systems Engineer (MCSE) and Microsoft Certified Systems Administrator (MCSA). Michael is one of the best .NET developers in the middle east and he's now working as .NET Trainer in his country Egypt. Michael has been writing code since he was 17 years old starting out with C coding, Michael had the fortunate opportunity to exposed to a variety of Programming languages, Database Management Systems and computer operating systems in spite of being young (21 years old).He is using the latest Microsoft Technologies to develop cutting-edge business applications. Michael is very active in the .NET world especially in C# and now he is writing his first certification kit for exams (70-316, 70-315 and 70-320) for MCAD.NET. Michael has been working with many different technologies and programming languages like ( C, C++, VB, VB.NET, C#, SQL Server 7.0, SQL Server 2000, XML, ASP, ASP. NET, XML Web Services, Network Design and implementation on Windows 2000 Platform). Michael is an international .NET Trainer and his students from all over the world (USA, UK, AUS, Egypt and many other countries).In his spare time, He test business applications and new software developed using .NET Platform.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
WEB USER CONTROL by Tom On February 2, 2008
Thank you very much for your easy to follow and well prepared explanation in your article. I am new to programming in C#. I wonder if you can help me in this. I am trying to create a generic WEB USER CINTROL using C# version 2.0. The functionality of this control is to have 5-buttons (FIRST,LAST, PERVIOUS , NEXT, SERACH). This control to be used by any .NET pages on the website and function as it suppose to. Meaning just drop this control on any page and be working. So for example a user can click on First , Last, etc,,.. and can go to the first record or last record, previous, or next. It does not matter if there is a GRIDVIEW, DATALIST or whatever on the page. Tom
Reply | Email | Delete | Modify | 
How can get the All methods list in .net? by Hemanth On October 31, 2009
Hi every one .plz tell me how can id get the all methods list in any format?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.