i made a class named x;
so i want to make array of it using dynamic allocation
x [] myobjects = new x();
but it gives me that error
Cannot implicitly convert type 'ObjAssig4.x' to 'ObjAssig4.x[]'
i know it's dump question but i am a beginner
thanks
x[] myobjects = new x[10];
For an array you don't create a new one with parens 'new x()'
An array is not dynamic though.
You could use Array.Resize to alter it's size, but you're probably after a List
List<x> myobjects = new List<x>();
myobjects.add(new x());
You don't want to use an array but a list
List<SomeObject> myObjects = new List<SomeObject>();
FYI you were declaring the array wrong too.
It should be
x[] myobjects = new x[5];
x [] myobjects = new x[numberOfElements];
Creates an array of numberOfElements references to objects of type x. Initially those references are null. You have to create the objects x independently and store references to them in Your array.
You can create an array and some objects whose references will end up in the array, using an initialisation list like:
x [] myobjects = new x[3] {new x(), new x(), new x()};
i Found that i can do this
x [] myobjects = new x[]{
new myobjects{//prop. goes here},
new myobjects{//prop. goes here}
}
The error
Cannot implicitly convert type
'ObjAssig4.x' to 'ObjAssig4.x[]'
is telling you that you are trying to declare a new x and assign it to your array. Instead, you need to declare a new array (which will also need a size):
x[] myobjects = new x[100];
Related
What is the correct way to define a List holding arrays of objects of type T?
Each array holds only 2 objects.
Based on this definition:
working: double[] balance = new double[10];
I tried
not working: List<T[]> arrList = new List<T[2]>();
I need to build a list that looks like
([obj1,obj2] ... [objn,objm] ...)
Thank you
D.
There is no way to use a fixed-size for the arrays in the list. You have to do this:
List<T[]> arrList = new List<T[]>();
and then trust the outside code that each array added to the list will have exactly two items.
The only other options I can think of right now are using tuples:
List< (T,T) > arrList = new List< (T,T) >();
or creating your own class type for the List with an indexer property and exactly two members.
Am I misunderstanding what ConvertAll does or just not understanding something, because I took it to be change the type and not just cast.
So I'm wondering how a StringBuilder (or any class) can be converted to another base class (or in this case object) and still keep its data and type.
StringBuilder[] y = new StringBuilder[] { new StringBuilder("a"), new StringBuilder("b"), new StringBuilder("c") };
object[] objectArray1 = Array.ConvertAll<StringBuilder, object>(y, (x2) => (object)x2);
In the above, the new array is of objects, but still contains StringBuilder items. I thought the new array would be of the new type, so essentially lose all the original data, e.g. converting from int to string via a conversion would give you a brand new array of strings.
As in,
string[] array2 = Array.ConvertAll(array1,
element => element.ToString());
Would give you a new array of strings.
thanks.
What ConvertAll() does is change the type of the reference. So you have a StringBuilder reference, and you copy that reference to a variable of type object:
var builder = new StringBuilder();
builder.AppendLine("Hello, World!");
object converted = (object)builder;
Now converted holds an object reference, but the actual object it's pointing to still is the StringBuilder that you instantiated.
The same is happening in the delegate you create. You can't just cast something to a base class and "cut off" all parts that aren't in the base class.
If you have a scenario where you think you need this, create a custom conversion.
I have a question about Enumerable.Repeat function.
If I will have a class:
class A
{
//code
}
And I will create an array, of that type objects:
A [] arr = new A[50];
And next, I will want to initialize those objects, calling Enumerable.Repeat:
arr = Enumerable.Repeat(new A(), 50);
Will those objects have the same address in memory?
If I will want to check their hash code, for example in that way:
bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();
This will return me true, and if I will change one object properties, all other objects will change it too.
So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?
Using Enumerable.Repeat this way will initialize only one object and return that object every time when you iterate over the result.
Will those objects have the same address in memory?
There is only one object.
To achieve what you want, you can do this:
Enumerable.Range(1, 50).Select(i => new A()).ToArray();
This will return an array of 50 distinct objects of type A.
By the way, the fact that GetHashCode() returns the same value does not imply that the objects are referentially equal (or simply equal, for that matter). Two non-equal objects can have the same hash code.
Just to help clarify for Camilo, here's some test code that shows the issue at hand:
void Main()
{
var foos = Enumerable.Repeat(new Foo(), 2).ToArray();
foos[0].Name = "Jack";
foos[1].Name = "Jill";
Console.WriteLine(foos[0].Name);
}
public class Foo
{
public string Name;
}
This prints "Jill". Thus it shows that Enumerable.Repeat is only creating one instance of the Foo class.
When using the following code to create an array:
var foos = Enumerable.Repeat(new Foo(), 2).ToArray();
The reason why each location in the array is the same is because you are passing an object, and not a function that creates an object, the code above is the same as:
var foo = new Foo();
var foos = Enumerable.Repeat(foo , 2).ToArray();
The reason above also explains why using a Select statement, like in the code below, creates a new object for each entry, because you are passing a function that dictates how each object is created, rather than the object itself.
Enumerable.Range(1, 2).Select(i => new Foo()).ToArray();
I would use a simple for loop to populate an array with new reference types.
I'm looking for a way to initialize a variable of type List with a set of values (in C#). Yes, there is object initialization but that requires a new object for each value you want and I would rather avoid it.
Here's a sample:
class MyObject
{
public string Name {get;set;}
}
List<MyObject> OldNames = new List<MyObject>(10);
List<MyObject> NewNames = new List<MyObject>(5);
This is fine and dandy but OldNames contains 10 null references to an object of type MyObject.
Using a list initializer I could do this:
List<MyObject> OldNames = new List<MyObject>{
new MyObject(),
new MyObject(),
new MyObject(),
etc.
That's kind of a pain as I have many list variables and various sizes to initialize (for exaample one variable is a list of 26 objects. Yes, I could write a function or maybe extension to do this initialization for me (in a loop where I provide the size) but again that's code I don't necessarily want to write.
I'm hoping there's some kind of lamdba or LINQ expression or something to initialize a list of objects to values instead of nulls.
Thanks!
Use the Enumerable.Range LINQ method to specify the number of iterations.
List<MyObject> NewNames = Enumerable.Range(1,5).Select(i => new MyObject()).ToList();
The number 1 here is arbitrary, as the indexer is not used in any way.
Just a quick musing... you can use Enumerable.Repeat... just not the way it's been done before. This would work:
var query = Enumerable.Repeat<Func<MyObject>>(() => new MyObject(), count)
.Select(x => x())
.ToList();
I'm not suggesting you should do this, but it's an interesting alternative to Enumerable.Range.
Create yourself a create and initialize function.
public List<T> CreateAndInitialize<T>(int size, Func<int, T> init)
{
var result = new List<T>(size);
for (int i = 0; i < size; ++i)
result.Add(init(i));
return result;
}
Then
List<MyObject> newNames = CreateAndInitialize(15, i => return new MyObject());
I chose to pass in the index of the object in the init delegate so that you could account for that if needed.
Looks to me you are just missing the () parenthesis after the new declaration.
private List<MyObject> ObjectList = new List<MyObject>()
{
new MyObject() { property1= Value1, property2 = "Value2"},
new MyObject() { property1= Value1, property2 = "Value2"}
};
I need to convert the linq query from generic ienumerable to arraylist.
ArrayList myArrayList = new ArrayList();
var b =
(from myObj in myCollection
select new myClass
{
Name = myObj.Name,
ac = myObj.ac
});
I have tried doing
b.Cast<ArrayList>();
but it is not working.
Edited :
I got it working with #devdigital solution
but i will also want to point out that at same time i found a hackish solution.
myArrayList.InsertRange(0, b.ToArray());
One of the constructors for the ArrayList type takes an ICollection, so you should be able to do the following:
var b =
(from myObj in myCollection
select new myClass
{
Name = myObj.Name,
ac = myObj.ac
}).ToArray();
ArrayList myArrayList = new ArrayList(b);
I'd suggest you to use a List<T> rather than an ArrayList. You can actually use the ToList extension method or the List's constructor which takes an IEnumerable<T>:
var myList = b.ToList(); // either
var myListTwo = new List<myClass>(b); // or
List<T> was newly introduced with .NET 2.0 and is generic. This means it yields you values of your actual type at compile-time, which is myClass, instead of object.
Edit: If you actually need an ArrayList, you need to copy b twice, as it cannot deal with IEnumerable directly, as devdigital pointed out in his reply:
ArrayList arrayList = new ArrayList(b.ToArray());
You can convert your IEnumerable to an array with ToArray(), then construct an ArrayList from that array.
var b = (from myObj in myCollection
select new myClass
{
Name = myObj.Name,
ac = myObj.ac
});
var myArrayList = new ArrayList(b.ToArray());
ArrayList arrayList = new ArrayList(b.ToList());