Part Three, Return Objects from a Method.

Part of the You Can Learn C# series.
By Ken Brown
September 5, 2004

This is part 3 of a three part article on Using Methods, calling a Method, and returning values from a method, this part focuses on returning objects from a Method.

Using Methods and Calling a Method in C#
Passing Objects to a Method
Returning Values from a Method.

The third and final part to this tutorial on C# Methods, covers how to return values from a Method. To review, we learned how to create a method, then how to send in additional information to the Method and now we want to return newly created information back to the object that originally called the method.

To demonstrate this functionality, we are going to make some changes to the Activate Button event. We are going to type in a number in the textbox and then multiply that number by 12 within the ChangeLabel method and then pass the value back to the Activate button event.
  1. Change the code from what you had to the following
    private void btnActivate_Click(object sender, System.EventArgs e)
         int intOutput = 0;
         intOutput = ChangeLabel(Convert.ToInt32(txtInput.Text));
         txtInput.Text = intOutput.ToString();

    private int ChangeLabel(int intBeginVal)
         lblAnswer.Text = "Beginning value is " + intBeginVal.ToString();
         intBeginVal *= 12;
         return intBeginVal;

  2. You also need to go to the Page_Load event and comment out the ChangeLabel Method call in that event or you will get an error message when you go to build the project.
  3. Run the Application and type in the number 2 into the text box. Press the Activate button and you should get something that looks like:
    Returning values from a Method call

Let's analyze what is occurring line by line.

  1. You have just pressed the Activate button. The first line to run is
    int intOutput = 0;
    Here you are creating a variable, an int and initializing it to 0.
  2. Then you fire the method
    intOutput = ChangeLabel(Convert.ToInt32(txtInput.Text));
    Notice that you start by having intOutput =. This means whatever the method returns must be able to be accepted by an int. Any other objects, like strings, booleans, or DataSets will cause a compiler error. Next I have slightly altered the ChangeLabel call to send in the txtInput.Text value, but converted it to an integer before it reaches the actual method.
  3. At this point the program will go into the ChangeLabel method. Notice that I have changed the method to look like this:
    private int ChangeLabel(int intBeginVal)
    The void after the word private has been changed to int. This means that this method must return an object of int or you will get a compiler error. The error will say something along the lines of "Cannot implicitly convert type "string" to "int"".

    The object being passed in has also been changed to an int with a variable name of intBeginVal, which we will use as we traverse the method.
  4. Then we are going to give our label the value originally passed to the method.
    lblAnswer.Text = "Beginning value is " + intBeginVal.ToString();.
  5. The next step we are going to use an old C++ trick of multiplying the value passed in by itself.
    intBeginVal *= 12;
    So intBeginVal will now equal 12 times whatever number you typed into the textbox.
  6. We return the calculated value from the previous step.
    return intBeginVal; It is very important ***** You must have the word return and the proper returned object. Nothing else happens after the word return, the code immediately returns to the calling method with the value in whatever object is after the word return.
  7. Finally, we come back to the event that called the method with the return object. We can do anything we want with the object that is returned. In this case we are going to display it inside the text box, so we can visually compare the values passed and the value returned.
    txtInput.Text = intOutput.ToString();
There you have it, how to create a method, pass a value to the method, do some type of processing within the method and then return some other object back to the calling object. Sometimes people look at this process and say it can't be this easy, but in reality the use of methods really is simple. It is the same process over and over again, with many different methods allowing programmers to create complex object-oriented programs. Remember, the goal is to make methods reusable, so you never have to write the same code more than once. As you are architecting your project, any time you see you need the same functionality, a red light should go off in your head and you should say, I need a method here.

Go To Page  1 / 2 / 3

Home| About Us | NewsLetters | Contact Us |

Copyright © 2004-2014 You Can Learn Series

You Can Learn Series Home Page You Can Learn Series
You Can Learn Series Home Page Home            About the creators of YouCanLearnSeriesAbout Us      Contact YouCanLearnSeriesContact Us      Site map of YouCanLearnSeriesSite Map      Privacy Policy of You Can Learn SeriesPrivacy Policy       Terms of Use of You Can Learn Series web siteTerms of Use       YouCanLearnSeries RSS feed for C# tips and tutorials     
C# and ASP.Net Programming TipsC# and ASP.Net      SQL Tutorial, tips and tricks for DBA'sSQL       Landscaping Tips for Home GardenersLandscaping       WeightLifting Tips for the Young and OldWeightLifting       Kennos BlogBlog       Good health TipsGoodHealth       Learn about Great Travel DestinationsTravel     Web Business TipsWeb Business            You Can Learn Series' Online StoreStore

You Can Learn C# and ASP.Net SeriesC# and ASP.Net
  Using Client Side Code with C# and ASP.NetClient Side Code
  Using Client Side State Management with C# and ASP.NetClient Side State Management
  Create a C# Class in Visual StudioCreate A Class
  Use A Class in C#Use A Class
  Create a Solution in Visual StudioCreate a Solution
  Create a Project in Visual StudioCreate a Project
  Create an RSS feed for your Web SiteCreate an RSS Feed
  Create an RSS feed for your Web SiteListItemCollection
  Set Events in ASP.NetSet Events ASP.Net
  Set Events in C#Set Events C#
  What is Session State and How to Use it.Session State
  Creating and Using the C# SortedList ObjectSortedList Object
  Stylesheet Tips for Visual Studio .Net and ASP.NetStyleSheet Tricks
  Using C# MethodsUsing Methods
  Pass Objects to MethodsPass Objects to Methods
  Pass Objects from MethodsPass Objects from Methods
  Using Client side State management like ViewState and Hidden fieldsView State
  LDAP, What is Lightweight Directory Access ProtocolWhat is LDAP
  Build an LDAP ReaderBuild an LDAP Reader
  Convert information from LDAP to a Web ServiceLDAP To Web Service
  Question of the dayQuestion of the Day

You Can Learn SQL SeriesSQL
You Can Learn Landscaping and Gardening SeriesLandscape Tips
You Can Learn WeightLifting SeriesWeightLift Tips
Kenno's BlogBlog
You Can Learn Good Health SeriesGood Health Tips
You Can Learn Good Series NewslettersNewsletters
Learn about Great Travel DestinationsTravel
You Can Learn Series Web Business TipsWeb Business Tips
Merchandise Available from You Can Learn SeriesMerchandise

Bill Welter - The Prepared Mind of a Leader

Americas Public Schools