Hi guys, I need your help:

I tried to initialize an array like this:

string[] relation1;

then I fill it with another function that contains the code:

for loop then:
relation1[z] = something;

but...compiler always writes that:

relation1' is never assigned to, and will always have its default value null

I've read somewhere that I need to initialize arrays with:

string[] relation1 = new string[50];

but my array needs to stay DYNAMIC so I cannot assign 50 items to it!
how to solve that issue?
and whats the difference between

string[] relation1;

and

string[] relation1 = new string[50];

why I cannot use simpler method that should work:

string[] relation1;

?
It was working in my another program, and I dont see much difference between both of them :/
Anyway I need it dynamic!

THX in advance for your help

Recommended Answers

All 3 Replies

You can pass it as a referrence parameter in a function and have that function allocate it.

You can also just use an empty List<string> lst_str = new List<string>(); and the function can populate it without having to call new on it.

using System.Collections.Generic;
using System.Linq;

namespace DW_413211_CS_CON
{
   class Program
   {
      public static void PutSomethingInArray(ref string[] arr_str)
      {
         arr_str = new string[3] { "this", "is", "neat" };
      }

      public static void PutSomethingInList(List<string> lst_str)
      {
         (new string[] { "this", "is", "neat" })
            .ToList().ForEach(s => lst_str.Add(s));
      }

      static void Main(string[] args)
      {
         string[] arr_str = null;
         PutSomethingInArray(ref arr_str);

         List<string> lst_str = new List<string>();
         PutSomethingInList(lst_str);
      }
   }
}

I dont see much difference between both of them :/

Then you need to go back and learn what an object is.

And List<T> is for dynamic 'arrays'

Thanks for your help guys!
everything is working fine now...
But please tell me.
whats the point of using "string[] relation1;"? can you write me small example?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.