-1

I can't figure out why

static void Main(string[] args)
{
    string nullstr=null;
    string teststring=string.Format("{0}", nullstr + (char)('A'+1));
    Console.WriteLine("After concatenating null string and char = " + test string);
}

is correct and run OK but

public void setName(string prefix=null)
{
    for(int i=0; i<Count; i++)
    {
        something[i].Name = string.Format("{0}", prefix+(char)('A'+i));
    }
}

is failed by calling in somewhere in program code.

setName();

setName() function is defaulted by string with null but it throws System.NullReferenceException

I am using Visual Studio 2015.

Francesco
  • 121
  • 7
  • 1
    Are you sure NullReferenceException is with prefix? – Sateesh Pagolu Dec 23 '16 at 03:38
  • Your code declares `nullstr` but never uses it and uses `nullptr` but never declares it. Is this the code you are actually working with? – Abion47 Dec 23 '16 at 03:44
  • See the marked duplicate for extensive advice on diagnosing and fixing `NullReferenceException`. If after reading the advice carefully and following it, you are still having trouble, post a new question in which you've included a good [mcve] that reliably reproduces the problem, and explain precisely what you've tried to debug the problem, and what _specifically_ you are still having trouble with. – Peter Duniho Dec 23 '16 at 04:09

2 Answers2

1

You might want to double check content of something[i]. Exception must be with this..

something[i].Name
Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48
1

Other than the typos in the code you presented, it runs fine when reformatted:

static void Main(string[] args)
{
    string nullstr = null;
    string teststring = string.Format("{0}", nullstr + (char)('A' + 1));
    Console.WriteLine("After concatenating null string and char = " + teststring);

    Console.WriteLine(setName(10, "_"));
}

public static string setName(int count = 0, string prefix = null)
{
    string str = "";
    for (int i = 0; i < count; i++)
    {
        str += string.Format("{0}", prefix + (char)('A' + i));
    }
    return str;
}

// Prints the following:
//
// After concatenating null string and char = B
// _A_B_C_D_E_F_G_H_I_J

Therefore, your NullReferenceException must be coming from the objects you are assigning the string to. Either something or something[i] is null.

Abion47
  • 22,211
  • 4
  • 65
  • 88