0

I'm investigating C# and some code where the string:

sheet.Cells[startRowIndexHeader, 11].Value = _currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub.TryGetCaption();

is inserting some text value in some excel cell. When I tried to change this Cub by the string:

currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub.AttributeCaption = "My value";

I recived the message

Object reference does not point to an instance of an object

How to change the Cub value?

By the way the code of TryGetCaption() functions which I found in this script:

public static string TryGetCaption(this ClassifierItem value)
{
    return value == null ? null : value.AttributeCaption;
}

public static string TryGetCaption(this DirectRoute value)
{
    var routeAsIp = value as CustomTCPClientRoute;
    if (routeAsIp != null)
        return string.Format("{0}: {1}", routeAsIp.AttributeHostOrIP, routeAsIp.AttributePort);
    return value == null ? null : value.Caption;
}

public static string TryGetCaption(this EnumerationItem value)
{
    return value == null ? null : value.Caption;
}
Boris Garkoun
  • 127
  • 2
  • 12
  • So what part of currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub.AttributeCaption is null ? – auburg Mar 07 '19 at 15:05
  • 1
    Do a null check: `if (obj.Cub != null) obj.Cub.AttributeCaption = " ... ";` – Peter B Mar 07 '19 at 15:06
  • 1
    Notice that those extension methods do a `null` check first. You should do the same... :) – Rufus L Mar 07 '19 at 15:15
  • Also they aren't following the typical `TryGet` pattern, which returns a `bool` indicating success and sets an `out` parameter to the value (or the default on failure). Those methods above should be named something like `GetCaptionOrDefault` – Rufus L Mar 07 '19 at 15:17

1 Answers1

0

currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub is null so you can not assign value to its properties. Check if it is null or not before assigning:

if(currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub != null)
currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub.AttributeCaption = "My value";
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • Thank you @Ashkan! If Cub is null so why the excel cell is not null and contains the value from `_currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub.TryGetCaption()` ? – Boris Garkoun Mar 11 '19 at 08:46