Method Parameters Keywords in C# – ref, out, params with Examples

You can add keywords to method parameters in C#.

The three of them are: ref, out and params.

ref

The ref keyword can be used to pass arguments by reference. That means the parameter can be changed in the method and the changed value will be retained when control passes back to the calling method. Ref parameters need to be initialized before passing.

Example

 public class RefMethodParameterDemo
    {
        //The ref keyword causes arguments to be passed by reference.
        //The effect is that any changes made to the parameter in the method will
        //be reflected in that variable when control passes back to the calling method.

        public static void RefParamMethod1(ref int num1, ref int num2)
        {
            num1 = 20;
            num2 = 40;
        }

        static void Main()
        {
            //Need to be initialized before passing as argument
            int n1 = 0;
            int n2 = 0;

            //Both the method definition and the calling method
            //must explicitly use the ref keyword.
            RefParamMethod1(ref n1, ref n2);
            Console.WriteLine("n1 = " + n1);
            Console.WriteLine("n2 = " + n2);
            Console.Read();
        }
    }

o/p

n1 = 20
n2 = 40

out

The out keyword can be used to pass arguments by reference.

This is similar to the ref keyword, except that out doesn’t require the variable be initialized before being passed.

Example

class OutMethodParameterDemo
    {
        //A method with out parameter is useful when you want a method to return multiple values.
        //The method definition must explicitly use the out keyword
        //The method is required to assign a value before the method returns.
        public static void OutParamMethod1(out int num1, out string str1)
        {
            num1 = 20;
            str1 = "Hi I am out";
        }

        static void Main()
        {
            //No need to initialize the variable before passing
            int n1;
            string s1;
            //Both the method definition and the calling method must explicitly use the out keyword
            //The out keyword causes arguments to be passed by reference.
            OutMethodParameterDemo.OutParamMethod1(out n1, out s1);
            Console.WriteLine(n1);
            Console.WriteLine(s1);

            Console.Read();
        }
    }

o/p
20
Hi I am out

params

The params keyword lets you create a method parameter that takes an argument where the number of arguments is variable.

When you don’t know the exact number of arguments that will be passed in a method, then you can declare the method parameters using the params keyword.

Example

 public class ParamsParameterDemo
    {
        //The params keyword lets you specify a method parameter that
        //takes an argument where the number of arguments is variable.
        public void ParamsMethod1(params int[] numlist)
        {
            for (int i = 0; i < numlist.Length; i++)
                Console.WriteLine(numlist[i]);
            Console.WriteLine();
        }

        //In a method declaration, no additional parameters are permitted after the params keyword
        public void ParamsMethod2(params string[] strlist)
        {
            for (int i = 0; i < strlist.Length; i++)
                Console.WriteLine(strlist[i]);
            Console.WriteLine();
        }

        //Only one params keyword is permitted in a method declaration
        public void ParamsMethod3(params object[] objlist)
        {
            for (int i = 0; i < objlist.Length; i++)
                Console.WriteLine(objlist[i]);
            Console.WriteLine();
        }

        static void Main()
        {
            ParamsParameterDemo p1 = new ParamsParameterDemo();

            //Passing many integer values
            p1.ParamsMethod1(1, 7, 19, 25);

           //Passing Array as an argument
            int[] arr1 = { 5, 7, 9, 20, 16,22 };

            p1.ParamsMethod1(arr1);

            //Passing a string array
            string[] strarr1 = { "Mona", "Tony", "Jia" };
            p1.ParamsMethod2(strarr1);

            //Passing any datatype(objects)
            p1.ParamsMethod3(12, 'C', "Remo");

            Console.Read();
        }
    }

o/p
1
7
19
25

5
7
9
20
16
22

Mona
Tony
Jia

12
C
Remo

Displaying, Adding, Updating and Removing Records using DataGridView Control in Windows Forms Application

We have shifted..

https://programmingpalace.wordpress.com/ is now http://thetechstory.com/

Find this Tutorial in the given link.

http://thetechstory.com/2012/09/18/displaying-adding-updating-and-removing-records-using-datagridview-control-in-windows-forms-application/

Connecting Multiple Databases in .NET using C# – Part 2 Building the UI and Final Application

This is part 2 of the Tutorial Series Connecting Multiple Databases in .NET using C#. We will see the UI and the final application in this part.

UI

Make a Select DB Form, Search Contact Form and Advance Search Form. Add reference of BL and BO here.

Snapshots of the UI is as below

SelectDBForm

SearchContactForm

AdvanceSearchForm

The code behind this files.

SelectDatabaseForm.cs

namespace UI
{
    public partial class SelectDatabaseForm : Form
    {
        public SelectDatabaseForm()
        {
            InitializeComponent();
            comboBoxSelectDB.SelectedIndex = 0;
        }

        //string sDatabase will store the selected Database of the user
        public static string sDatabase = string.Empty;

        private void buttonGo_Click(object sender, EventArgs e)
        {
            if (comboBoxSelectDB.Text == string.Empty)
            {
                MessageBox.Show("Select a Database to connect first");
            }
            else
            {
                sDatabase = comboBoxSelectDB.Text;
                SearchContactForm frmSearch = new SearchContactForm();
                this.Hide();
                frmSearch.ShowDialog();
            }
       }//Button Go Click event end here.
    }
}

SearchContactForm.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BO;
using BL;

namespace UI
{
    public partial class SearchContactForm : Form
    {
        public SearchContactForm()
        {
            InitializeComponent();
            textBoxContactId.Focus();
        }

        //Fetching the Selected Database Name from the SelectConnection Form
        private string sDatabase = SelectDatabaseForm.sDatabase;

        private void SearchContactForm_Load(object sender, EventArgs e)
        {
            //In case of Advanced Search when the Contact Id comes from the Advanced Search Form this is used
            if (textBoxContactId.Text != "")
            {
                showData();
            }

            labelDBName.Text = sDatabase;
            this.Text = "Search Contact Form || Selected Database - "+sDatabase;
        }

        #region showData Method
        //showData method is used to fetch Contact Details using Contact Id
        private void showData()
        {
            //Exception is thrown when the user enters invalid Contact Id like Characters
            //So we are putting the code in try block
            try
            {
                Int32 iContactId = Convert.ToInt32(textBoxContactId.Text);

                ContactBO objContactBO = new ContactBO();

                objContactBO = ContactBL.GetContactDetails(sDatabase, iContactId);

                //Searching Using Contact Id
                //Checking if Contact Id exists
                if (objContactBO.ContactId != 0)
                {
                    //Making the labels controls Visible which will display the Search Result
                    labelContactIdResult.Visible = labelNameResult.Visible = true;
                    labelMobileNumResult.Visible = labelEmailIdResult.Visible = true;
                    labelDOBResult.Visible = true;

                    //Displaying the Search Result in Label Controls
                    labelContactIdResult.Text = objContactBO.ContactId.ToString();
                    string sFName = objContactBO.FirstName;
                    string sLName = objContactBO.LastName;
                    sFName = sFName.Trim();
                    sLName = sLName.Trim();
                    labelNameResult.Text = sFName + " " + sLName;
                    labelMobileNumResult.Text = objContactBO.MobileNumber;
                    labelEmailIdResult.Text = objContactBO.EmailId;
                    labelDOBResult.Text = objContactBO.DOB.ToShortDateString();

                }

                else
                {
                    MessageBox.Show("Contact Id doesn't exist");
                    textBoxContactId.Focus();
                }
            }//try end

            //Here we are handling the exception
            catch (Exception ex)
            {
                MessageBox.Show("Invalid Contact Id");
                MessageBox.Show(ex.ToString());
            }

        }
        #endregion
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            //Searching using Contact Id
            if (textBoxContactId.Text != "")
            {
                showData();

            }
            //Searching Using First Name
            else if (textBoxFirstName.Text != "")
            {
                string sFName = textBoxFirstName.Text;

                List lstContactDetails = new List();
                lstContactDetails = ContactBL.GetContactDetails(sDatabase, sFName);

                //Checking if any Contact with the First Name Exists
                //The List will return zero if no contact is there with the First Name
                //Else Advanced Search Form will display with all the Contacts
                if (lstContactDetails.Count != 0)
                {
                    AdvancedSearchForm frmAS = new AdvancedSearchForm();
                    frmAS.textBoxFirstName.Text = sFName;
                    this.Hide();
                    frmAS.ShowDialog();
                }
                else
                {
                    MessageBox.Show("First Name doesn't exist");
                }

            }//Searching Using First Name ends

            else
            {
                MessageBox.Show("Enter a Contact Id or Name to search");
            }
        }

        //Code for LinkLabel Control Change Database
        private void linkLabelChangeDB_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDatabaseForm frmSC = new SelectDatabaseForm();
            this.Hide();
            frmSC.ShowDialog();
        }

    }
}

AdvancedSearchForm.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BO;
using BL;

namespace UI
{
    public partial class AdvancedSearchForm : Form
    {
        public AdvancedSearchForm()
        {
            InitializeComponent();
        }

        //Fetching the Selected Database Name from the SelectConnection Form
        private string sDatabase = SelectDatabaseForm.sDatabase;

        private void AdvancedSearchForm_Load(object sender, EventArgs e)
        {
            string sFName = textBoxFirstName.Text;
            List lstContactDetails = new List();

            lstContactDetails = ContactBL.GetContactDetails(sDatabase, sFName);

            dataGridViewContactDetails.DataSource = lstContactDetails;
        }

        //Make the DataGridView Control Read Only so that the user can't edit the values.
        //When the user clicks on a Particular Contact here then Search Contact Form displays with the Contact Details
        private void dataGridViewContactDetails_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string sContactId = dataGridViewContactDetails.SelectedCells[0].Value.ToString();
            SearchContactForm frmSF = new SearchContactForm();
            frmSF.textBoxContactId.Text = sContactId;
            this.Hide();
            frmSF.ShowDialog();
        }
    }
}

Screenshots of Running the Application

User needs to select the Database when the application starts. Here the user selects the Sql Server DB.

SelectDBForm_Running

Search Contact Form Displays when the user clicks on the Go Button. Here the user can search a Contact using either Contact Id or First Name. In this form we are also displaying the Selected DB name and we are also giving an option to the user to change the DB at runtime.

SearchFormOpens_with_DBSqlServer

Searching Using First Name

Searching_using_FirstName

Advanced Search Form displays showing all the contacts with the same First Name. Here in this Form also, we need to access the Database Name we selected previously.

AdvancedSearchFormOpens

When the user clicks on a contact in DataGridView Control, then it details get displayed in Search Contact Form.

AdvancedSearchDisplaysinSearchForm

When the user clicks on Change Database Link, then Select DB Form appears. Now the user can select another DB. This time the user select Oracle.

ChangingDatabaseAtRunTime

Searching Contact Using Oracle DB.

SearchContact_using_OracleDB

Done for the Day. Happy Programming. 😀

.NET Project Demonstrating MVC Pattern using C# – Contact Information Management System(CIMS)-Part 6-Adding a New Contact

We have shifted..

https://programmingpalace.wordpress.com/ is now http://thetechstory.com/

Find this Tutorial in the given link.

http://thetechstory.com/2012/09/27/net-project-demonstrating-mvc-pattern-using-c-contact-information-management-systemcims-part-6-adding-a-new-contact/

.NET Project Demonstrating MVC Pattern using C# – Contact Information Management System(CIMS)-Part 5-Deleting a Contact

Deleting a Contact

When the User clicks on Delete LinkLabel Control in the WelcomeForm or AdvanceSearch Form, a Message Box pops us asking the user whether he really wants to delete the contact. Based on the user selection the contact gets removed.

The Code in WelcomeForm.cs for Delete Link Label Control click event is below


   //Code for Delete Link Control
        private void linkLabelDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Int32 iContactId = Convert.ToInt32(labelContactIdResult.Text);

             DialogResult result1= MessageBox.Show("Are you sure you want to delete this Contact?",
                                   "Delete the Contact",
                                    MessageBoxButtons.YesNo);

             if (result1 == DialogResult.Yes)
             {
                 int result = ContactBL.RemoveContact(iContactId);

                 if (result > 0)
                 {
                     MessageBox.Show("Contact Removed Successfully");
                 }
             }

        }

In the WelcomeForm.cs, in the Delete Link click event, we are opening a Message Box with Yes, No Buttons. If the user select Yes then we are calling a Method called RemoveContact  in ContactBL taking the Contact Id of the User as an Input Parameter.


  public static int RemoveContact(Int32 iContactId)
        {
            int result = ContactDL.DeleteContactDetails(iContactId);
            return result;
        }

This method calls a method in ContactDL called  DeleteContactDetails

 public static int DeleteContactDetails(Int32 iContactId)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("DELETE FROM contact_details WHERE ContactId = @Id", conn);

                cmd.Parameters.Add(new SqlParameter("@Id", iContactId));

                int result = cmd.ExecuteNonQuery();

                conn.Close();
                return result;

            }
            catch (Exception e)
            {
                throw e;
            }

        }

This method deletes the Contact from the Database table.

Snapshots of Removing a Contact.

Select a contact for Deleting and click on the Delete link. 

SelectContactForDeleting

A message box appears asking whether you want to delete or not.

UserCanSelectWhetherToDeleteOrNot

When the user select Yes the Contact get removed and a message box pops us giving a Confirmation Message.

IfUserSelectsYesThenContactGetParmanentlyRemoved