Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » C# Language » C# Methods

C# Methods

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

Page Views : 127295
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate 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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
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 | Modify 
How can get the All methods list in .net? by Hemant On October 31, 2009
Hi every one .plz tell me how can id get the all methods list in any format?
Reply | Email | Modify 
struggling by prince On May 5, 2010
im am struggling to create methods that work with lists
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.