0

Perhaps I didn't explaine myself the first time around so here is my second go at it.

I need to declare objects from a list of strings inside an array.

So my array goes out to a DB and collects the names from one colums. This names will all be an object. Now I want to define each object with that name fromt he column dynamicly.

So the array has say 5 elements in it of type string.

So going though my for look i cannot seem t o dynamicly create the object.

So instead of manually going myobject test = new myobject();

I just want to declare it by looping though the array.

3
  • 2
    How would the object's members be defined/assigned? What does your class look like? The compiler is pretty smart but it probably can't predict which members to assign which array values to. Commented May 30, 2011 at 17:47
  • the type of "myArray" is array of MyObject? (MyObject[]) Commented May 30, 2011 at 17:49
  • The question is unclear to me, do you mean "how do you clone an object in an array so that the object in the array is in separate memory from the object I am trying to access?" Commented May 30, 2011 at 17:49

3 Answers 3

2

I'am not pretty sure what your question is, but if I see your code than you want to create objects in your array?

Maybe this is your solution:

MyObject[] myArray = new MyObject[4];
for (int i =0; i < myArray.Length; ++)
{    
myArray[i] = new MyObject();
}

Hope this will help you.

Sign up to request clarification or add additional context in comments.

Comments

0
MyObject[] myArray = new MyObject[3];
for (int i =0; i < myArray.Length; i++)
{
    MyObject obj = new MyObject();
    myArray[i] = obj;
}

1 Comment

I want to make an object out of the element in the ray. So say Myarray[1] holds the value test. I want to assign that as an object.
0

You can convert an array to objects by using System.Linq's select operator. You create an object for every i in the array and return a new object for it like this

var array = new string[2]{"one","two"};
var objects = array.Select(i=> new Object{Name = array[i]}).ToArray();

2 Comments

var's are not data types in C#
var indicates that the compiler should infer the type for you..this way you don't need to type int[] and Object[]. It has been in C# since 3.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.