I know i am making a silly mistake but unfortunately i am unable to find it even after a lot of Debug. I have made a class "naivebayes" and other class Connect
======================== This is a method of Connect==================
public NaiveBayes[] ReadOBj()
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand command = new SqlCommand(@"SELECT NAME, CODE, DEPARTMENT, TS, CD, REPEAT, CORE, [Content], Grade FROM Transcript WHERE (Grade <> 'UNKNOWN')", conn);
SqlDataReader reader = null;
reader=command.ExecuteReader();
NaiveBayes[] a=new NaiveBayes[10];
NaiveBayes1.NaiveBayes na = new NaiveBayes();
int i = 0;
while (reader.Read())
{
i++;
string Namee = (string)reader["NAME"];
Console.WriteLine(Namee);
na.Name = Namee;
string depte=reader["DEPARTMENT"].ToString();
na.Dept = depte;
string core= reader["CORE"].ToString();
Boolean.TryParse(core,out na.Core);
string rpet=reader["REPEAT"].ToString();
Boolean.TryParse(core,out na.Repeat);
int tse,cde;
int.TryParse(reader["TS"].ToString(),out tse) ;
int.TryParse(reader["CD"].ToString(),out cde);
na.TS=tse;
na.CD=cde;
string contente=reader[7].ToString();
na.Content = contente;
string grade=reader["Grade"].ToString();
na.Grade = grade;
a[i] = na;
}
conn.Close();
return a;
}
1) The problem is when i try to access attributes of NaiveBayes it gives null reference exception.
Forexample :
a[i].Name="ABC";
This will raise the following Exception.
Unhandled Exception: System .NullReferenceException :Object Reference is not set to an instance of object
2)The 2nd problem is that all object in a[i] must have distinct values but the value is replicated(of last iteration)
Forexample when i=2 ,and a[1].Name was "IstName" .and a[2].Name must be "2ndName". At the end both a[1].Name and a[2].Name has same value"2ndName"
================================This is NaiveBayes class======================
namespace NaiveBayes1
{
public class NaiveBayes
{
public string Name ;
public string Dept ;
public string Content ;
public string Grade ;
public Boolean Core ;
public Boolean Repeat;
public int TS ;
public int CD ;
public NaiveBayes()
{
Name = "";
Dept = "";
Content = "";
Grade = "";
Core = false;
Repeat = false;
TS = 0;
CD = 0;
}
}
================Answer of Problem 2========================
NaiveBayes[] na = new NaiveBayes[5];
NaiveBayes[0].Name ="ABC" // NaiveBayes[0] is null. The array was allocated but not initialized.
// There is no NaiveBayes class to set the Name for.
Full Answer is here What is a NullReferenceException, and how do I fix it?