0

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?

Community
  • 1
  • 1
Charlie
  • 4,262
  • 1
  • 28
  • 50
  • 2
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Alberto Mar 05 '14 at 13:32

3 Answers3

3

Your first error comes most probably from the fact, that there are less than 10 rows in your DB, so not all of 10 array elements are being set.

The second problem is because you assign the same instance to each array element. Simplest fix:

NaiveBayes[] a=new NaiveBayes[10];
NaiveBayes1.NaiveBayes na;

int i = 0;
while (reader.Read())
{
    na = new NaiveBayes();
    i++;

One proposed solution for the first problem is to use list instead of an array:

List<NaiveBayes> nbs = new List<NaiveBayes>();

int i = 0;
while (reader.Read())
{
    NaiveBayes1.NaiveBayes na = new NaiveBayes();
    i++;

    //...

    nsb.Add(na);
}

So then when you attempt to use it, you can verify the desired index against nbs.Count property. Or you can return it from your method using .ToArray().

BartoszKP
  • 32,105
  • 13
  • 92
  • 123
1

I think this:

NaiveBayes1.NaiveBayes na = new NaiveBayes();

should be in the while loop so you get a new one on each loop, otherwise your just adding the same object each time.

Lee Willis
  • 1,477
  • 9
  • 14
1

Your database is a general select statement but you are expecting exactly ten records back. If there are less than 10 records, you will get the Null Reference Exception, if there are more than 10, you will get an Index Out of Range Exception. To work around this, use a List or another resizeable container.

Also, the second issue of repeated values is possibly because you are reusing the instances of NaiveBayes class within the loop.

Also, as quite a few variables are acting as intermediaries between the data reader and object, I have simplified.

public NaiveBayes[] ReadOBj()
{
    SqlConnection conn = new SqlConnection(connectionString);
    SqlCommand command = new SqlCommand(@"SELECT NAME, CODE, DEPARTMENT, TS, CD, REPEAT,        CORE, [Content], Grade 
    FROM Transcript
    WHERE (Grade <> 'UNKNOWN')", conn);

    conn.Open();
    SqlDataReader reader = command.ExecuteReader();
    List<NaiveBayes> a = new List<NaiveBayes>();

    while (reader.Read())
    {
        NaiveBayes1.NaiveBayes na = new NaiveBayes();
        na.Name = (string)reader["NAME"];
        na.Dept = reader["DEPARTMENT"].ToString();
        Boolean.TryParse(reader["CORE"].ToString(), out na.Core);
        Boolean.TryParse(reader["REPEAT"].ToString(),out na.Repeat);
        int.TryParse(reader["TS"].ToString(),out na.TS) ;
        int.TryParse(reader["CD"].ToString(),out na.CD);
        na.Content = reader["Content"].ToString();
        na.Grade = reader["Grade"].ToString();

        a.Add(na);
    }

    conn.Close();
    return a.ToArray();
}
Kami
  • 18,269
  • 4
  • 43
  • 62