making Array of objects of a class

  • Thread starter Muhammad Aftab Alam
  • Start date
M

Muhammad Aftab Alam

Hello All
The question might be somewhat stupid but I have tried for an hour and could
not get through it.

I am creating a console based application just to begin with C#

following is the code
namespace Student1

{

class ABC

{

private

string strname;

public void GetData()

{

Console.WriteLine("Enter your Name");

strname = Console.ReadLine();

}

public void Print()

{

Console.WriteLine(strname);

}

};

class Class1

{

[STAThread]

static void Main(string[] args)

{


ABC[] arr = new ABC[6];

arr[0].GetData(); // This Line gives exception?

arr[0].Print();


}

}

}



according to me it should display a string to get data then print it but the
an exception occurs.System.NullRefrenceException

the Message is "Object reference not set to an instance of an object."

best regards

Aftab
 
F

Frank Oquendo

Muhammad said:
ABC[] arr = new ABC[6];

All you have is array capable of holding ABC objects, not an array of
actual ABC objects.

You'll have to initialize the array manually.
 
C

clyyy2002

try to

using System;
using System.Collections;

namespace Student1

{

class ABC

{

private

string strname;

public void GetData()

{

Console.WriteLine("Enter your Name");

strname = Console.ReadLine();

}

public void Print()

{

Console.WriteLine(strname);

}

};

class Class1

{

[STAThread]

static void Main(string[] args)

{


ABC[] arr = new ABC[6];

for(int i=0;i<arr.Length;i++)
{
arr = new ABC();
}

arr[0].GetData(); // This Line gives exception?

arr[0].Print();


}

}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top