Object reference not set to an instance of an object

R

RP

I have created a DLL called as ADFormula which contains public
functions. After adding reference of this DLL in my project, I want to
call the functions contained there in. For this I am using following
code:

//Iniialize object instance
ADFormula.Class1 objADFormula = new ADFormula.Class1();

//Call routine
objADFormula.GenerateALL();

It generates error on line [objADFormula.GenerateALL();]

Error: Object Reference not set to an Instance of an Object.

What is the cause of this?
 
J

Jon Skeet [C# MVP]

RP said:
I have created a DLL called as ADFormula which contains public
functions. After adding reference of this DLL in my project, I want to
call the functions contained there in. For this I am using following
code:

//Iniialize object instance
ADFormula.Class1 objADFormula = new ADFormula.Class1();

//Call routine
objADFormula.GenerateALL();

It generates error on line [objADFormula.GenerateALL();]

Error: Object Reference not set to an Instance of an Object.

What is the cause of this?

Well, you've got a null reference somewhere. If your code is *exactly*
as shown, then objADFormula itself shouldn't be null, but perhaps the
GenerateALL method is throwing the exception?
 
R

RP

Below is the code of ADFormula DLL:
============================================================================
using System;
using System.Collections.Generic;
using System.Text;

namespace ADFormula
{
public class Class1
{

ModReusable objModReusable = new ModReusable();
Global objGlobal = new Global();

public void GenerateALL()
{
//Initialize Pay Generation Flag to lock closing.
objGlobal.PayGenerationInProgress = true;

//Fetch Employee IDs from EmpADSettings Table.
string qAllEmpIds = "Select distinct(EmpID) from
EMPADSettings order by EmpID";
objModReusable.FillDataSet(qAllEmpIds, "AllEmpIds");

Int64 TotalEmployees =
objModReusable.ds.Tables["AllEmpIds"].Rows.Count;
//loop for all employees
for (int i = 0; i < TotalEmployees; i++)
{
Int64 empID =
Convert.ToInt64(objModReusable.ds.Tables["AllEmpIds"].Rows[0]);

//Check ServiceStatus of this employee.
//Because Pay is to be generated only for: REGULAR,
WITHHELD employees.
string qServiceStatus = "Select ServiceStatus from
EmpOfficialMaster where EmpID=" + empID;
string SerStatus =
objModReusable.ReturnOneField(qServiceStatus);

switch(SerStatus.Trim())
{
case ("REG"):
{
string qBasicPay = "Select CurrentPayScale
from EmpOfficialMaster where EmpID=" + empID;
double basicPay =
Convert.ToDouble(objModReusable.ReturnOneField(qBasicPay));

string qAllADCodes = "Select ADCode from
EMPADSettings where EmpID=" + empID;
objModReusable.FillDataSet(qAllADCodes,
"AllADCodes");

//loop for all ADCodes of an Employee
for (int j = 0; j <
objModReusable.ds.Tables["AllADCodes"].Rows.Count; j++)
{
string adCode =
objModReusable.ds.Tables["AllADCodes"].Rows[j][0].ToString();

//check CalculationMethod(Direct or
Formula)
string qCalcMethod = "Select
CalculationMethod from ADMaster where ADCode='" + adCode + "'";
string CalculationMethod =
objModReusable.ReturnOneField(qCalcMethod);

switch (CalculationMethod)
{
case ("D"):
{
string qPer = "Select
DesiredValue from EMPADSettings where EmpID=" + empID + " and
ADCode='" + adCode + "'";
double PerOrAmount =
Convert.ToDouble(objModReusable.ReturnOneField(qPer));

//check and calculate
Percentage
string qIfCalcPer =
"Select CalculatePercent from ADMaster where ADCode='" + adCode + "'";
string ifCalcPer =
objModReusable.ReturnOneField(qIfCalcPer);

double adAmount = 0;
if (ifCalcPer == "N")
{
adAmount =
PerOrAmount;
}
else if (ifCalcPer == "Y")
{
adAmount =
Math.Floor((basicPay * PerOrAmount) / 100 + 0.5);
}

//check and calculate
Dearness Pay
if (adCode ==
"DEAR.PAY") //Dearness Pay and DA are calculated simultaneously
because DA depends upon Basic Pay and Dearness Pay
{
//save Dear.Pay in
EmpSalaryRecord
string qSaveDearPay =
"Insert into EmpSalaryRecord values(";
qSaveDearPay =
qSaveDearPay + "'" + DateTime.Now.ToString("yyyy-MM-dd") + "',";
qSaveDearPay =
qSaveDearPay + "" + empID + ",";
qSaveDearPay =
qSaveDearPay + "'" + adCode + "',";
qSaveDearPay =
qSaveDearPay + "'-',";
qSaveDearPay =
qSaveDearPay + "" + adAmount + ",";
qSaveDearPay =
qSaveDearPay + "'" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") +
"',";
qSaveDearPay =
qSaveDearPay + "" + objGlobal.ActiveUserID + ")";

try
{
Int32 result =
objModReusable.InsertNewRecord(qSaveDearPay);
}
catch (Exception ex)
{
}

//Calculate Dearness
Allowance [DA] from Dearness Pay and Basic Pay
adAmount =
Math.Floor(((basicPay + adAmount) * 20) / 100 + 0.5);
adCode = "DA";
}

//For Installments,
increment last installment no.
string qIfCalcInst =
"Select CalculateInstallment from EMPADSettings where EmpID=" + empID
+ " and ADCode='" + adCode + "'";
string ifCalcInst =
objModReusable.ReturnOneField(qIfCalcInst);

string instNo = "";
if (ifCalcInst == "N")
{
instNo = "-";
}
else if (ifCalcInst ==
"Y")
{
string qLastInstNo =
"Select LastInstallmentNo from EMPADSettings where EmpID=" + empID + "
and ADCode='" + adCode + "'";
Int32 lastInstNo =
Convert.ToInt32(objModReusable.ReturnOneField(qLastInstNo));
Int32 currentInstNo =
lastInstNo + 1;

string qTotalInst =
"Select TotalInstallmentNo from EMPADSettings where EmpID=" + empID +
" and ADCode='" + adCode + "'";
Int32 totalInst =
Convert.ToInt32(objModReusable.ReturnOneField(qTotalInst));

instNo = currentInstNo
+ "/" + totalInst;
}

//save record in
EmpSalaryRecord
//string qEmpCode =
"Select EmpCode from EmpPersonalMaster where EmpID=" + empID;
//double empCode =
Convert.ToDouble(objModReusable.ReturnOneField(qEmpCode));

string qSave = "Insert
into EmpSalaryRecord values(";
qSave = qSave + "'" +
DateTime.Now.ToString("yyyy-MM-dd") + "',";
qSave = qSave + "" + empID
+ ",";
qSave = qSave + "'" +
adCode + "',";
qSave = qSave + "'" +
instNo + "',";
qSave = qSave + "" +
adAmount + ",";
qSave = qSave + "'" +
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "',";
qSave = qSave + "" +
objGlobal.ActiveUserID + ")";

try
{
Int32 result =
objModReusable.InsertNewRecord(qSave);
}
catch (Exception ex)
{

objGlobal.PayGenerationInProgress = false;
}

//update LastInstallmentNo
in EMPADSettings
if (ifCalcInst == "Y")
{
string
qUpdateLastInstNo = "Update EMPADSettings set
LastInstallmentNo=LastInstallmentNo+1 where EmpID=" + empID + " and
ADCode='" + adCode + "'";

try
{
Int32 res =
objModReusable.InsertNewRecord(qUpdateLastInstNo);
}
catch (Exception ex)
{

objGlobal.PayGenerationInProgress = false;
}
}
break;
}

case("F"):
{
switch (adCode)
{
case ("DA"):
{
//
CalculateDA();
break;
}
}
break;
}
}

}
break;
}

case ("WH"):
{
string qAllADCodes = "Select ADCode from
EMPADSettings where EmpID=" + empID;
objModReusable.FillDataSet(qAllADCodes,
"AllADCodes");

//loop for all ADCodes of an Employee
for (int j = 0; j <
objModReusable.ds.Tables["AllADCodes"].Rows.Count; j++)
{
string adCode =
objModReusable.ds.Tables["AllADCodes"].Rows[j][0].ToString();

//save record in EmpSalaryRecord
string qSave = "Insert into
EmpSalaryRecord values(";
qSave = qSave + "'" +
DateTime.Now.ToString("yyyy-MM-dd") + "',";
qSave = qSave + "" + empID + ",";
qSave = qSave + "'" + adCode + "',";
qSave = qSave +
"'-',"; //Installment No.
qSave = qSave +
"0,"; //AD Amount
qSave = qSave + "'" +
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "',";
qSave = qSave + "" +
objGlobal.ActiveUserID + ")";

try
{
Int32 result =
objModReusable.InsertNewRecord(qSave);

}
catch (Exception ex)
{
objGlobal.PayGenerationInProgress
= false;
}
}
break;
}
}
StoreGrossNetPay(empID, DateTime.Now);
objGlobal.ProgressBarMin = i;
}
objGlobal.PayGenerationInProgress = false;
//Return Success or Failure
}
}
======================================================================
 
P

Peter Duniho

RP said:
Below is the code of ADFormula DLL:
[...snip...]

That's way too much code to post, especially for an issue like this.

You have a reference variable that is being used without it being
initialized to an actual reference. It still has its default value of null.

The debugger is generally very helpful in telling you what variable is
null, if you simply look at the line that generates the exception and
then check all of the values in the line. Having variable-less
references (eg a reference returned by a method) makes it harder; in
that case, it's often helpful to create variables to store the
references temporarily so that you can look at them more easily in the
debugger (if you look at the assembly, you can tell what's null
regardless, but this isn't always a useful suggestion for someone).

If the exception is actually happening within some other code that
you're calling, then the call stack will show that other code's stack
frame at the top, even if there's no symbols or source. Your own code
will show the green "call entered here" marker, rather than being
highlighted in yellow in this case. If that's happening, then it could
either be because you've passed in null for something that shouldn't be
(though typically methods will check parameters for null and throw an
argument-related exception if one is null), or there could be a bug in
the code you're calling (which you can do little about if it's code out
of your control...which would be the usual reason you don't have the
symbols or source for the code).

Basically, this is a really good opportunity for you to learn more about
how to track down null references in the debugger. In reality, these
are often the easiest thing to debug, because the immediate cause of the
problem is readily apparent, always. That is, whatever's null, it's
null at the exact moment that the code breaks when it's null. Figuring
out why it's null is not always so straightforward, but at least you
should be able to tell what's null.

Pete
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

RP said:
I have created a DLL called as ADFormula which contains public
functions. After adding reference of this DLL in my project, I want to
call the functions contained there in. For this I am using following
code:

//Iniialize object instance
ADFormula.Class1 objADFormula = new ADFormula.Class1();

//Call routine
objADFormula.GenerateALL();

It generates error on line [objADFormula.GenerateALL();]

Error: Object Reference not set to an Instance of an Object.

Are you sure objADFormula contain a valid reference?
Is it possible that the GenerateALL() method is the one that is having the
error but you do not have the source code for it?
Take a look at InnerException's property of the exception
 

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