Question

is it possible to create an array of SqlConnection? For expample;

SqlConnection[] con = new SqlConnection[4];
con[0].ConnectionString = "my connection string";

when write this code it gives no error but when you run it it says:

Object reference not set to an instance of an object.
Was it helpful?

Solution 3

After:

SqlConnection[] con = new SqlConnection[4];

This...

con[0].ConnectionString = "my connection string";

..is equivalent to:

SqlConnection con; // Type defined, but no instance!
con.ConnectionString; 

What you want is the equivalent of:

SqlConnection con = new SqlConnection();
// Accessible, since you now have an instance:
con.ConnectionString = "some string"; 

In your case:

var con = new SqlConnection[4];
con[0] = new SqlConnection();
con[0].ConnectionString = "my connection string"

OTHER TIPS

You are not assigning the objects in the array list, it should be

con[0] = new SqlConnection("my connection string");

Moreover when you write,

var con = new SqlConnection[4];

it does not mean that you have created four new objects of SqlConnection rather it states an Array object is created which will be holding refrence to four SqlConnection objects.
So for storing the objects first you need to create them and then assign them to Array.
Example

con[0] = new SqlConnection("my connection string 1");
con[1] = new SqlConnection("my connection string 2");
con[2] = new SqlConnection("my connection string 3");
con[3] = new SqlConnection("my connection string 4");
var con = new SqlConnection[4];
con[0] = new SqlConnection("my connection string");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top