Thursday, September 8, 2011

Arrays with C# Classes

Arrays with C# Classes

Arrays works as collections of items, for instance strings. You can use them to gather items in a single group.

Here Below Example i created a Class called Name. In which we have a Two variables, A constructor expecting two inputs First and Last name. and a property that returns Full Name of a Person Name.

Its a very simple example where i am putting all Names in to an array called GroupOfFriends. Printing all Names is very easy you can use either For loop or Foreach Loop. I used Foreach.

I used WebSite page to work on this example:

.cs Code Calling Class Name from Page_Load

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class September_Sep08 : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        //Creating few instances for Class Name
        Name emmu = new Name("Emmaneale", "Mendu");
        Name vamshi = new Name("Vamshi", "Malyala");
        Name pradeep = new Name("Pradeep", "Kandula");

        //Creating an Array to maintain Group of Names
        Name[] GroupOfFriends = { emmu, vamshi, pradeep };

        Response.Write("List of Names in the FriendsList:<br/>");

        //Using foreach to print the Names
        foreach (Name p in GroupOfFriends)
            Response.Write(p.FullName + "<br/>");

    public class Name
        string FirstName;
        string LastName;

        //Constructor for our Class
        public Name(string first, string last)
            FirstName = first;
            LastName = last;

        //public property for FullName
        public string FullName
                return FirstName + " " + LastName;

Your outPut looks like below Figure

No comments:

Post a Comment