here is a small part of the code if anyone has ideas feel free to hoit me up!
public decimal getBook(string pair, decimal amount, string type, string operation, bool division = true)
{
try
{
//book is null
BinanceOrderBook book = null;
foreach (var item in Program.array)
if ((item as Program.ClassDetailOrder).symbol == pair.ToLower())
{
book = (item as Program.ClassDetailOrder).book; break;
}
// 'lst' is also null nut lst depends on book to not be null. lst is a list but created on the results of the ifs below (ask and bid are api calls )
List<BinanceOrderBookEntry> lst = null;
if (type == "asks")
lst = book.Asks;
if (type == "bids")
lst = book.Bids;
decimal[] arrayValue = new decimal[2];
arrayValue[0] = arrayValue[1] = 0;
decimal orderPrice = 0;
decimal orderAmount = 0;
decimal totalCost = 0;
decimal totalAmount = 0;
decimal remaining = amount;
decimal cost = 0;
foreach (var item in lst)
{
orderPrice = item.Price;
orderAmount = item.Quantity;
cost = orderPrice * orderAmount;
if (cost < remaining)
{
remaining -= cost;
totalCost += cost;
totalAmount += orderAmount;
}
else
{
//finished
remaining -= amount;
totalCost += amount * orderPrice;
totalAmount += amount;
if (division)
{
arrayValue[0] = Math.Round(amount / (totalCost / totalAmount), 8);
arrayValue[1] = Math.Round(amount / orderPrice, 8);
}
else
{
arrayValue[0] = Math.Round((totalCost / totalAmount) * amount, 8);
arrayValue[1] = Math.Round(orderPrice * amount, 8);
}
return arrayValue[0];
}
}
}
catch (Exception ex)
{
}
}
If I correctly understand your application architecture, adding a few null-checks may solve your issue.
Your models:
Your array of
ClassDetailOrderwith some values (exampled):Calling
GetBookmethod with different parameters:And your
GetBookmethod (with few my additions, changes and comments):The main idea, that you should understand, is to check every nullable object for possible null value where you can. In this example we possibly may have 8 objects, which could be
nulland may causeNullReferenceException. And you can handle them all:arrayofClassDetailOrder(to be able search forClassDetailOrderitems in it);pairvalue (to avoid null exception when lowercasing withToLower());ClassDetailOrder(to avoid null exceptions while searching forBook);ClassDetailOrderat result (if no one was found byFirstOrDefaultmethod);Book(to be sure that we can access it'sAsks/Bidslists);typevalue (to be sure be can take properList(Asks or Bids or any other you will have));List(to be sure, thatListat least empty, but not null);BinanceOrderBookEntryitem inforeachloop overList(to be sure we can access itsPriceandQuantityproperties).You can handle null-checks in a way you wish or return value you wish or reverse
ifs tois not null(!= null) way.You can tests different values to try cover all null-checks and test them.