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 » Programming C#: Working with Arrays in .NET

Programming C#: Working with Arrays in .NET

This tutorial discusses arrays programming in C# and .NET. It starts with the discussion of simple arrays and then delves more complex topics such as jagged and multi-dimensional arrays. In the end, it discusses the Array class and its methods for searching and soring an array items.

Author Rank:
Total page views :  1384369
Total downloads :  1431
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ArraysTutorialsWordDoc.zip
 
Become a Sponsor



Description

Programming C# is a new self-taught series of articles, in which, you may learn C# programming in a simple step by step tutorial format.

This article concentrates on arrays in .NET and how you can work with arrays using C# language. Article also covers the Arrays class and its methods, which can be used to sort, search, get, and set an array items.

Introduction

In C#, an array index starts at zero. That means, first item of an array will be stored at 0th position. The position of the last item on an array will total number of items - 1.

In C#, arrays can be declared as fixed length or dynamic. Fixed length array can stores a predefined number of items, while size of dynamic arrays increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined. For example, the following like declares a dynamic array of integers.

int [] intArray;
The following code declares an array, which can store 5 items starting from index 0 to 4.

int [] intArray;
intArray = new int[5];

The following code declares an array that can store 100 items starting from index 0 to 99.

int [] intArray;
intArray = new int[100];

Single Dimension Arrays

Arrays can be divided into four categories. These categories are single-dimensional arrays, multidimensional arrays or rectangular arrays, jagged arrays, and mixed arrays.

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored in a row starting from 0 to the size of array -1.
In C# arrays are objects. That means declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.

The following code declares a integer array, which can store 3 items. As you can see from the code, first I declare the array using [] bracket and after that I instantiate the array by calling new operator.

int [] intArray;
intArray = new int[3]; yahoo Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared.
The following code declares and initializes an array of three items of integer type.

int [] intArray;
intArray = new int[3] {0, 1, 2};

The following code declares and initializes an array of 5 string items.
string
[] strArray = new string[5] {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

You can even direct assign these values without using the new operator. 

string
[] strArray = {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

You can initialize a dynamic length array as following
string[] strArray = new string[] {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

Multi Dimension Arrays


A multidimensional array is an array with more than one dimension. A multi dimension array is declared as following:
string[,] strArray;

After declaring an array, you can specify the size of array dimensions if you want a fixed size array or dynamic arrays. For example, the following code two examples create two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array can store 4 items respectively.

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] names = new string[2, 2] { {"Rosy","Amy"}, {"Peter","Albert"} };

If you don't want to specify the size of arrays, just don't define a number when you call new operator.
For example,

int
[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] names = new string[,] { {"Rosy","Amy"}, {"Peter","Albert"} };
 
You can also omit the new operator as we did in single dimension arrays. You can assign these values directly
without using the new operator. For example:


int
[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Rosy", "Amy"}, {"Peter", "Albert"} };







Jagged Arrays

Jagged arrays are often called array of arrays. An element of a jagged array itself is an array. For example, you can define an array of names of students of a class where a name itself can be an array of three strings - first name, middle name and last name. Another example of jagged arrays is an array of integers containing another array of integers. For example,

int[][] numArray = new int[][] { new int[] {1,3,5}, new int[] {2,4,6,8,10} };

Again, you can specify the size when you call the new operator.

Mixed Arrays


Mixed arrays are a combination of multi-dimension arrays and jagged arrays. Multi-dimension arrays are also called as rectangular arrays.

Accessing Arrays using foreach Loop


The foreach control statement (loop) of C# is a new to C++ or other developers. This control statement is used to iterate through the elements of a collection such as an array. For example, the following code uses foreach loop to read all items of numArray.

int[] numArray = {1, 3, 5, 7, 9, 11, 13};
foreach (int num in numArray)
{
System.Console.WriteLine(num.ToString());
}

A Simple Example


This sample code listed in Listing 1 shows you how to use arrays. You can access an array items by using for loop but using foreach loop is easy to use and better.
Listing 1. Using arrays in C#.
using
System;
namespace
ArraysSamp
{
class
Class1
{
static void Main(string
[] args)
{
int[] intArray = new int
[3];
intArray[0] = 3;
intArray[1] = 6;
intArray[2] = 9;
Console.WriteLine("================");
foreach (int i in
intArray)
{
Console.WriteLine(i.ToString() );
}
string[] strArray = new string
[5]
{"Ronnie", "Jack", "Lori", "Max", "Tricky"};
Console.WriteLine("================");
foreach( string str in
strArray)
{
Console.WriteLine(str);
}
Console.WriteLine("================");
string[,] names = new string
[,]
{
{"Rosy","Amy"},
{"Peter","Albert"}
};
foreach( string str in
names)
{
Console.WriteLine(str);
}
Console.ReadLine();
}
}
}
#region Web Form Designer generated code
override protected void
OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base
.OnInit(e);
}
/// <summary>
///
Required method for Designer support - do not modify
///
the contents of this method with the code editor.
///
</summary>
private void
InitializeComponent()
{
this.Load += new System.EventHandler(this
.Page_Load);
}
#endregion
}
}

The output of Listing 1 looks like Figure 1.

Figure 1.

Understanding the Array Class


The Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class but it provides CreateInstance method to construct an array. The Array class provides methods for creating, manipulating, searching, and sorting arrays.
Table 1 describes Array class properties. 

IsFixedSize

Return a value indicating if an array has a fixed size or not.

IsReadOnly

Returns a value indicating if an array is read-only or not.

IsSynchronized

Returns a value indicating if access to an array is thread-safe or not.

Length

Returns the total number of items in all the dimensions of an array.

Rank

Returns the number of dimensions of an array.

SyncRoot

Returns an object that can be used to synchronize access to the array.


Table 1: The System.Array Class Properties
Table 2 describes some of the Array class methods.

BinarySearch

This method searches a one-dimensional sorted Array for a value, using a binary search algorithm.

Clear

This method removes all items of an array and sets a range of items in the array to 0.

Clone

This method creates a shallow copy of the Array.

Copy

This method copies a section of one Array to another Array and performs type casting and boxing as required.

CopyTo

This method copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.

CreateInstance

This method initializes a new instance of the Array class.

GetEnumerator

This method returns an IEnumerator for the Array.

GetLength

This method returns the number of items in an Array.

GetLowerBound

This method returns the lower bound of an Array.

GetUpperBound

This method returns the upper bound of an Array.

GetValue

This method returns the value of the specified item in an Array.

IndexOf

This method returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array.

Initialize

This method initializes every item of the value-type Array by calling the default constructor of the value type.

LastIndexOf

This method returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.

Reverse

This method reverses the order of the items in a one-dimensional Array or in a portion of the Array.

SetValue

This method sets the specified items in the current Array to the specified value.

Sort

This method sorts the items in one-dimensional Array objects.


Table 2: The System.Array Class Methods

The Array Class
Array class is an abstract base class but it provides CreateInstance method to construct an array.
Array names = Array.CreateInstance( typeof(String), 2, 4 );

After creating an array using the CreateInstance method, you can use SetValue method to add items to an array. I will discuss SetValue method later in this article.
The Array class provides methods for creating, manipulating, searching, and sorting arrays. Array class provides three boolean properties IsFixedSize, IsReadOnly, and IsSynchronized to see if an array has fixed size, read only or synchronized or not respectively. The Length property of Array class returns the number of items in an array and the Rank property returns number of dimensions in a multi-dimension array.
Listing 1 creates two arrays with a fixed and variable lengths and sends the output to the system console.
int [] intArray;
// fixed array with 3 items
intArray = new int
[3] {0, 1, 2};
// 2x2 varialbe length array
string[,] names = new string
[,] { {"Rosy","Amy"}, {"Peter","Albert"} };
if
(intArray.IsFixedSize)
{
Console.WriteLine("Array is fixed size");
Console.WriteLine("Size :" + intArray.Length.ToString());
}
if
(names.IsFixedSize)
{
Console.WriteLine("Array is varialbe.");
Console.WriteLine("Size :" + names.Length.ToString());
Console.WriteLine("Rank :" + names.Rank.ToString());
}

Listing 1.
Besides these properties, the Array class provides methods to add, insert, delete, copy, binary search, reverse, reverse and so on.
Searching an Item in an Array
The BinarySearch static method of Array class can be used to search for an item in a array. This method uses binary search algorithm to search for an item. The method takes at least two parameters - an array and an object (the item you are looking for). If an item found in an array, the method returns the index of the item (based on first item as 0th item),  else method returns a negative value. Listing 2 uses BinarySearch method to search two arrays.
int [] intArray = new int[3] {0, 1, 2};
string[] names = new string
[] {"Rosy","Amy", "Peter","Albert"};
object
obj1 = "Peter";
object
obj2 = 1;
int
retVal = Array.BinarySearch(names, obj1);
if
(retVal >=0)
Console.WriteLine("Item index " +retVal.ToString() );
else

Console.WriteLine("Item not found");
retVal = Array.BinarySearch(intArray, obj2);
if
(retVal >=0)
Console.WriteLine("Item index " +retVal.ToString() );
else
Console.WriteLine("Item not found");

Listing 2. Searching an item in a array
Sorting Items in an Array

The Sort static method of the Array class can be used to sort an array items. This method has many overloaded forms. The simplest form takes a parameter of the array, you want to sort to. Listing 3 uses Sort method to sort an array items. 

string[] names = new string[] {"Rosy","Amy", "Peter","Albert"};
Console.WriteLine("Original Array:");
foreach (string str in
names)
{
Console.WriteLine(str);
}
Console.WriteLine("Sorted Array:");
Array.Sort(names);
foreach (string str in
names)
{
Console.WriteLine(str);
}

Listing 3. Sorting an array items. 
Getting and Setting Values

The GetValue and SetValue methods of the Array class can be used to return a value from an index of an array and set values of an array item at a specified index respectively. The code listed in Listing 4 creates a 2-dimension array instance using the CreateInstance method. After that I use SetValue method to add values to the array. 

In the end I find number of items in both dimensions and use GetValue method to read values and display on the console. 

Array names = Array.CreateInstance( typeof(String), 2, 4 );
names.SetValue( "Rosy", 0, 0 );
names.SetValue( "Amy", 0, 1 );
names.SetValue( "Peter", 0, 2 );
names.SetValue( "Albert", 0, 3 );
names.SetValue( "Mel", 1, 0 );
names.SetValue( "Mongee", 1, 1 );
names.SetValue( "Luma", 1, 2 );
names.SetValue( "Lara", 1, 3 );
int
items1 = names.GetLength(0);
int
items2 = names.GetLength(1);
for ( int
i =0; i < items1; i++ )
for ( int
j = 0; j < items2; j++ )
Console.WriteLine(i.ToString() +","+ j.ToString() +": " +names.GetValue( i, j ) );

Listing 4. Using GetValue and SetValue methods
Other Methods of Array Class

The Reverse static method of the Array class reverses the order of items in a array. Similar to the sort method, you can just pass an array as a parameter of the Reverse method. 

Array.Reverse(names); 

The Clear static  method of the Array class removes all items of an array and sets its length to zero. This method takes three parameters - first an array object, second starting index of the array and third is number of elements. The following code removes two elements from the array starting at index 1 (means second element of the array). 

Array.Clear(names, 1, 2); 

The GetLength method returns the number of items in an array. The GetLowerBound and GetUppperBound methods return the lower and upper bounds of an array respectively. All these three methods take at least a parameter, which is the index of the dimension of an array. The following code snippet uses all three methods. 

string[] names = new string[] {"Rosy","Amy", "Peter","Albert"};
Console.WriteLine(names.GetLength(0).ToString());
Console.WriteLine(names.GetLowerBound(0).ToString());
Console.WriteLine(names.GetUpperBound(0).ToString()); 

The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 5 copies contents of an integer array to an array of object types. 

// Creates and initializes a new Array of type Int32.
Array oddArray = Array.CreateInstance( Type.GetType("System.Int32"), 5 );
oddArray.SetValue(1, 0);
oddArray.SetValue(3, 1);
oddArray.SetValue(5, 2);
oddArray.SetValue(7, 3);
oddArray.SetValue(9, 4);
// Creates and initializes a new Array of type Object.
Array objArray = Array.CreateInstance( Type.GetType("System.Object"), 5 );
Array.Copy(oddArray, oddArray.GetLowerBound(0), objArray, objArray.GetLowerBound(0), 4 );
int
items1 = objArray.GetUpperBound(0);
for ( int
i =0; i < items1; i++ )
Console.WriteLine(objArray.GetValue(i).ToString());
 

Listing 5. Copying an array.
You can even copy a part of an array to another array by passing number of items and starting item in the Copy method. The following format copies a range of items from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
public
static void Copy(Array, int, Array, int, int);
Summary
In this article, you learned basics of arrays and how arrays are handled and used in C#. In the beginning of this article, we discussed different types of arrays such as single dimension, multi dimension, and jagged arrays. After that we discussed the Array class. In the end of this article, we saw how to work with arrays using different methods and properties of Array class.


Login to add your contents and source code to this article
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
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  
Download Files:
ArraysTutorialsWordDoc.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Multidimensional Array by a On August 30, 2006
What is the meaning of the following multidimensinal array declartion :

int [ , , ] arr=new int[4,2,3];

please elaborate.
Reply | Email | Delete | Modify | 
Re: Multidimensional Array by Jason On April 24, 2007

You are creating an three dimensional array of type int. The array is called arr and the new command creates a new three dimentional array with the dimensions are 4x2x3. When I think of an array, I think of an excel spreadsheet. The a one dimensional array is a row, a two dimensional array is a a row x column, and a three dimensional array is a row x column x page.

Reply | Email | Delete | Modify | 
Re: Multidimensional Array by mohit On May 10, 2007

hello the declaration u gave:

int[,,] arr=new int[3,2,5]

clearly means we 've declared a 3-dimensional array of int having 3*2*5 no.of elements

i.e.say for example

3 is length

2 is width

5 is height

Reply | Email | Delete | Modify | 
Re: Multidimensional Array by Unais On February 14, 2008

hi

it is the syntax to declare a multidimensional array.its just like the one we used to declare in c++.

in C++

datatype arrayname[size][size][size];

similarly

int [ , , ] arr=new int[4,2,3];

shows an integer array type in three dimension{int[,,]arr},the comma seperation shows the 3 dimensional or three sets of array.

new int[4,2,3] shows the size of each dimensions or set of values where first one will have 4,second with 2 & 3rd with3,

thats all.hope u understood. still need clarification just mail me in unaisk@yahoo.co.in 

Reply | Email | Delete | Modify | 
Multi dimensional array by dola On November 22, 2006

Hello,

I read your article on arrays. Nice article

Please can you help with codes on implementing a multidimensional array for  a database that has 5 tables , and each table has 5 attributes and 12 records .

 

How do i populate the tables using the code.

 

Thanks

Reply | Email | Delete | Modify | 
Re: Multi dimensional array by mohit On May 10, 2007

hello

this problem suggests u need to delare an array of array

i.e.

int[][,] arr=new int[5][5,12]

where 1st array is an array of 5 databases

which in turn is a 2-d array having 5 attributes & 12 records

Reply | Email | Delete | Modify | 
ARRAY by Tavleen On April 25, 2007
How can we pick words from richtextbox and put them in array of strings? For example if the text of richtextbox is hi , how are you ? then the string array contains hi , how are you ? please reply
Reply | Email | Delete | Modify | 
Array by Tavleen On April 25, 2007
How can we pick words from richtextbox and put them in array of strings? For example if the text of richtextbox is hi , how are you ? then the string array contains {"hi" , "how" , "are" , "you" , "?" } please reply
Reply | Email | Delete | Modify | 
multidimensional array(matrix) by abhijeet On May 7, 2007
i want code for following example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Reply | Email | Delete | Modify | 
DYNAMIC CONTROLS ARAY by LIBERT On May 18, 2007
HI NICE TUTORIAL HELP ALOT I AM NEW AT C# ANDWAS DOING A SOFTWARE THAT REQUIRES THE USER TO ENTER A SERIES OF DATA IN A TABLE (X & Y) AND WAS TRYING TO MAKE A CONTROL THAT A CREATED OF TWO TEXT BOX AND WHEN THE USER HTS THE ADD BUTTON A NEW CONTROL WILL APPEAR UNDER THE FIST ONE
Reply | Email | Delete | Modify | 
Re: DYNAMIC CONTROLS ARAY by Mahesh On May 19, 2007
You can create a Struct with two members and create an ArrayList object filled with the struct. Alternatively, you may want to use HashTable class.
Reply | Email | Delete | Modify | 
print the contents? by kiki On August 5, 2007
how can I print the contents of a Multi Dimension Array like string[,] s=new string[20,3]; usining Response.Write() for showing the content?? thank you for your help
Reply | Email | Delete | Modify | 
Re: print the contents? by Mahesh On August 8, 2007
I guess you want to display contents on a Web page? I would use an HTML table and add TR and TDs to it.
Reply | Email | Delete | Modify | 
Re: Re: print the contents? by kiki On August 9, 2007
let's say that I want to print the contents in a row, the one under the other, without using td and tr. I try to do it using a for(...) repeating procedure and there are meny errors which I don't understand... can you give me an example? thank you
Reply | Email | Delete | Modify | 
hello by emani On August 7, 2007
how i can use the sorting (selection & exchanging) for these variables 16 8 12 21 24 11 25 in microsoft visual j++ 6.0 thnk you
Reply | Email | Delete | Modify | 
unknown size by alex On August 28, 2007
Hi! Is it possible to create an array with dinamyc size? Let say we are reading rows from DB table or lines from a file?
Reply | Email | Delete | Modify | 
Re: unknown size by Avijit On August 30, 2007

You can better use ArrayList for that purpose. You have to import the System.Collections class

ArrayList al = new ArrayList();
al.Add(1);
al.Add(2);
al.Add(3);

 

Reply | Email | Delete | Modify | 
Array of object.. by admin On August 31, 2007
nice tutorial but i want array of text box? How to create this in C sharp? please reply
Reply | Email | Delete | Modify | 
Re: Array of object.. by Mahesh On September 4, 2007
You can user ArrayList class and add TextBox objects to it. When you retrieve textboxes from the ArrayList, you need to convert object to TextBox.
Reply | Email | Delete | Modify | 
data loading problem by Sathees On September 4, 2007
I have created an array instance as global . I used command click event to load data to this array. Another command click i created to display the content of array. But when I click it says erro messge "Object reference not set to an instance of an object.". But when i try from the previous click function it works. Any help please
Reply | Email | Delete | Modify | 
data loading problem by Sathees On September 4, 2007
I have created an array instance as global . I used command click event to load data to this array. Another command click i created to display the content of array. But when I click it says erro messge "Object reference not set to an instance of an object.". But when i try from the previous click function it works. Any help please
Reply | Email | Delete | Modify | 
Re: data loading problem by Mahesh On September 4, 2007
How did you create a global array?
Reply | Email | Delete | Modify | 
Re: Re: data loading problem by Sathees On September 5, 2007

In the web form after class definition I created it. So that it will be common to all command click events. Following is part of code the code..

 

public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage

{

protected System.Web.UI.MobileControls.Label Label1;

protected System.Web.UI.MobileControls.Label Label2;

protected System.Web.UI.MobileControls.Label Label3;

protected System.Web.UI.MobileControls.TextBox txtcompany;

protected System.Web.UI.MobileControls.TextBox txtarea;

protected System.Web.UI.MobileControls.SelectionList cmbselection;

protected System.Web.UI.MobileControls.Command cmdsearch;

protected System.Data.SqlClient.SqlConnection sqlConnection1;

protected System.Web.UI.MobileControls.Label Company;

protected System.Web.UI.MobileControls.TextView TextView1;

protected System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;

protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;

protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;

protected System.Web.UI.MobileControls.Command cmdhome;

protected System.Web.UI.MobileControls.Label Label4;

protected System.Web.UI.MobileControls.Command Command1;

protected System.Web.UI.MobileControls.Form Form1;

// ArrayList mylist = new ArrayList();

public string [] str = new string[50];

public Array names = Array.CreateInstance( typeof(string),50);

private void cmdsearch_Click(object sender, System.EventArgs e)

{

names.Setvalue(data,j);

}

private void Command1_Click(object sender, System.EventArgs e)

{

this.TextView1.Text = names.GetValue(1).ToString

}

Reply | Email | Delete | Modify | 
Re: Re: Re: data loading problem by Sathees On September 11, 2007
I did not receive any idea from you,please let me know what can i do...urgent
Reply | Email | Delete | Modify | 
i have problem in array computation by pieter On October 19, 2007
dear author, my name is pieter...i'm newbie in C-sharp. here is my program list: for ( i = 0; i <= u; i++) { z[i]=a * z[i-1] + c % 16; console.writeline(z[i]); } please check my short list program( because the program doesnt work properly), if don't mind please tell me if i have make a mistake. thank you very much. thank you very much....God Bless... warm greeting from indonesia....
Reply | Email | Delete | Modify | 
Re: i have problem in array computation by james On January 3, 2008
on the first iteration of loop i=0, therefore (i-1)=-1.  Therefore index of the z array becomes -1 which is most likely the reason behind your error.
Reply | Email | Delete | Modify | 
Property of an array by Roel On November 8, 2007
Hello, I have a class with an array as one of the fields. I want properties for all the fields, but I don't know how to do this with the array. Example: public class Player { private string name; public Player(string name) { this.name = name } public string Name { get { return name; } } } public class Team { private int number; private Player[] players; public Team(int number) { this.number = number; this.players = new Player[10]; public Player Player { get { ??? } set { ??? } } } } I can get or set a whole array, but how do I do get a specific item of the array? I tried: public Player Player(int i) { get { return players.GetValue(i); } set { players.setValue(value, i); } } but that doesn't work. Can anyone plz help me?
Reply | Email | Delete | Modify | 
size of array by sanj On February 25, 2008
i want to find ot the size of an array by using while loop as we are doing in C++ like while(str[i] != '\0') {i++;} this code is giving error of array out of bound even though my declared size is much more greater than entered array. plz help me why this is coming. can u tell me how length function is working in C#??????
Reply | Email | Delete | Modify | 
Re: size of array by Meena On October 15, 2008

int[] intArray;
            intArray = new int[3] { 0, 1, 2 };

            string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
            if (intArray.IsFixedSize)
            {
                Console.WriteLine("Array is fixed size");
                Console.WriteLine("Size :" + intArray.Length.ToString());
            }
            if (names.IsFixedSize)
            {
                Console.WriteLine("Array is varialbe.");
                Console.WriteLine("Size :" + names.Length.ToString());
                Console.WriteLine("Rank :" + names.Rank.ToString());
            }

Reply | Email | Delete | Modify | 
question by varun On February 28, 2008
how do u compare the equality of 2 diff arrays and also 2 diff strings?
Reply | Email | Delete | Modify | 
question by varun On February 28, 2008
how do u compare the equality of 2 diff arrays and also 2 diff strings?
Reply | Email | Delete | Modify | 
C# by Chellammal On March 5, 2008
Toaacept the total number of array elements and values from the user.To arrange elements in ascending order
Reply | Email | Delete | Modify | 
array by periyasami On October 1, 2008
very nice. Thank u
Reply | Email | Delete | Modify | 
Logic in c#.net by lakshmi On November 19, 2008
hello any body help me with this i need a logic of if i gave 250.50 in one textbox after clicking the button i should get the twohundread and fifty rupees and fifty paise in textbox2 i need logic please help me
Reply | Email | Delete | Modify | 
Re: Logic in c#.net by Mahesh On April 6, 2009
Please post your question on forums. See Forums link at the top header.
Reply | Email | Delete | Modify | 
Arrays by Steven On December 11, 2008
Sorry if this posted twice. I am trying to figure out a way for my program to figure out how many letters where used in what ever word I write in a textbox. For example if I write the word CAB, I want to a messagebox to display or a label to display "You used A 1 time" "You used B 1 time" "You used C 1 time" "You used D 0 times" ..... I don't know how to set up the array to do this. If you could help this very lost student, I would geatly appreciate it!
Reply | Email | Delete | Modify | 
Re: Arrays by Mahesh On April 6, 2009
Please post your question on forums. See Forums link at the top header.
Reply | Email | Delete | Modify | 
solve it by smita On January 6, 2009
Explain variable size arrays in c#
Reply | Email | Delete | Modify | 
Re: solve it by Mahesh On April 6, 2009
Please post your question on forums. See Forums link at the top header.
Reply | Email | Delete | Modify | 
Where can i get this array class by zain On April 15, 2009
Can someone provide the code for the array class in C?
Reply | Email | Delete | Modify | 
Re: Where can i get this array class by Mahesh On April 16, 2009
C does not have an Array class. Array class is a part of .NET Framework only.
Reply | Email | Delete | Modify | 
this article is wrong by ababab On June 17, 2009
This article is WRONG!

In C#, arrays can be declared as fixed length or dynamic. Fixed length array can stores a predefined number of items, while size of dynamic arrays increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined. For example, the following like declares a dynamic array of integers.

int [] intArray;


This is just plain wrong.  The above is NOT a declaration for a dynamic array.  The simplest way to get dynamic arrays in C# is with ArrayList.  The Array class is NOT dynamically sizable.

Perhaps the author was confused because Array implements the IList interface.  However, see this:

http://msdn.microsoft.com/en-us/library/system.array.isfixedsize(VS.71).aspx




Reply | Email | Delete | Modify | 
How initiate an array of objects? by Vadim On June 18, 2009

Hallo,

i have my class and want to create an array of my class' objects. How can i do it? I can't initiate it as
myclass[x] myarray = new myclass(par a, par b)[x];

Thanks

Reply | Email | Delete | Modify | 
Re: How initiate an array of objects? by danny On August 18, 2009
try like this:


                    MyClass[] myClassArray = new MyClass[100];
                    for(int i = 0; i < myClassArray.Length; i++)
                    {
                        myClassArray[i] = new MyClass(parama, paramb);
                    }



------------------------------
Danny, Los Angeles Locksmith
Reply | Email | Delete | Modify | 
arrays of object by gaby On July 1, 2009
hello,

I need a little help. I want to set up a array of object, but I can not handle very well.
public class inregistrare
    {
        public static int nr_crt;
        public inregistrare()
        {
            nr_crt++;
        }
        public static string data;
        public static int getnr_crt()
        {
            return nr_crt;
        }

inregistare[] array=new inregistrare[100];

for (int i=0; i<=100; 1++)
{
inregistrare.nr_crt=s.Substring(2,6);
inregistrare.data=...;//nevermind
??array[i]=inregistrare() ????? ;//here I don't know what to do in order to record all the information from inregistrare.nr_crt and inregistrare.data in array[i]
}

I'm just a beginner..

Thank you,
Reply | Email | Delete | Modify | 
how to read values from array to assign it to list members by lunatic On September 29, 2009

hi  I am a newbie in programming, so not very comfortable with arrays, list and collections stuff, currently working on an application for which I need to read values from an array (the values of array are gathered from an excel data sheet) and assign them to each individual member of the list,

its somewhat like this:

first value of array is assigned to first member of list

second value of array is assigned to second member of list and

so on..

I am having issues building the logic and code to make this work..

Wonder if you can help

Reply | Email | Delete | Modify | 
Example by sandip On November 11, 2009
Can u give simple example with for loop for 2D array..

Sandip
www.aikadajiba.blogspot.com
Reply | Email | Delete | Modify | 
Concept regarding TAG by Sachin On November 28, 2009
hello friend i am Sachin,  i am a beginner in .net , please tell me how access the drives present on the computer like c:,d: etc and also the subfolders.Please mail me the answer on my mail id : sgaikwad84@gmail.com
Reply | Email | Delete | Modify | 
Please help here by Loyiso On February 14, 2010

ABC Cookery class needs a program that will enable them to enter the marks of judges for the class’s  student demos. There are 10 students. Each student has a unique number between 1 and 10(both numbers included). Each student is judged by 3 judges. The marks for the 3 judges are input on Form1. The three marks are loaded into the columns of a 2D array, JudgesMarks. Each row is a student and the columns are the 3 judges’ marks for that student.

Reply | Email | Delete | Modify | 
thank you by krish On February 28, 2010
this is very useful to me.keep update.


by regards,
  krishna
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.