How to define an array with no hard coded size?

A

Andy B

I have this code:

public class Contract {
private Definition[] definitionField = new Definition[];
public Definition[] Definitions {
get {return value;}
set {definitionField=value;}
}
}

Then when I go to use it like this:

//create a contract
Contract Contract = new Contract();

//assign definitions to the definitions sections. These 2 lines create:
Error 2 Array creation must have array size or array initializer
Contract.Definitions[0].Word="Venue";
Contract.Definitions[0].Definition1="The place at which the event takes
place";
....

How do you make an array without having to define the array size?
 
J

Jon Skeet [C# MVP]

Andy B said:
I have this code:

public class Contract {
private Definition[] definitionField = new Definition[];
public Definition[] Definitions {
get {return value;}
set {definitionField=value;}
}
}

Then when I go to use it like this:

//create a contract
Contract Contract = new Contract();

//assign definitions to the definitions sections. These 2 lines create:
Error 2 Array creation must have array size or array initializer
Contract.Definitions[0].Word="Venue";
Contract.Definitions[0].Definition1="The place at which the event takes
place";
...
How do you make an array without having to define the array size?

You can't. Arrays are of a fixed size. If you want a dynamically sized
collection, look at List<T> instead.
 
C

CSharper

I have this code:

public class Contract {
private Definition[] definitionField = new Definition[];
public Definition[] Definitions {
get {return value;}
set {definitionField=value;}

}
}

Then when I go to use it like this:

//create a contract
Contract Contract = new Contract();

//assign definitions to the definitions sections. These 2 lines create:
Error 2 Array creation must have array size or array initializer
Contract.Definitions[0].Word="Venue";
Contract.Definitions[0].Definition1="The place at which the event takes
place";
...

How do you make an array without having to define the array size?

Try using ArrayList instead, by the way are you trying to build a
dictionary?
 
A

Andy B

Unless I'm wrong, the last I heard was that <list t> couldn't be serialized
into an xml file. It is required that the contract objects be stored inside
of xml files of some form or another (unless there are other ideas I don't
know about). is there any way to fix this?


Jon Skeet said:
Andy B said:
I have this code:

public class Contract {
private Definition[] definitionField = new Definition[];
public Definition[] Definitions {
get {return value;}
set {definitionField=value;}
}
}

Then when I go to use it like this:

//create a contract
Contract Contract = new Contract();

//assign definitions to the definitions sections. These 2 lines create:
Error 2 Array creation must have array size or array initializer
Contract.Definitions[0].Word="Venue";
Contract.Definitions[0].Definition1="The place at which the event takes
place";
...
How do you make an array without having to define the array size?

You can't. Arrays are of a fixed size. If you want a dynamically sized
collection, look at List<T> instead.
 
V

vvnraman

I have this code:

public class Contract {
private Definition[] definitionField = new Definition[];
public Definition[] Definitions {
get {return value;}
set {definitionField=value;}

}
}

Then when I go to use it like this:

//create a contract
Contract Contract = new Contract();

//assign definitions to the definitions sections. These 2 lines create:
Error 2 Array creation must have array size or array initializer
Contract.Definitions[0].Word="Venue";
Contract.Definitions[0].Definition1="The place at which the event takes
place";
...

How do you make an array without having to define the array size?

Hi Andy
One way to do that is to use an ArrayList.
An ArrayList works much in the same way as an array but it has all the
features you require.
You'll have to use it as
public class Contract
{
private ArrayList definitionField = new ArrayList();
public ArrayList Definitions
{
get { return value; }
set { definitionField = value; }
}
}

To add values to it you have to use the Add() method.
e.g.
Definition insertDef = new Definition();
insertDef.Word="Venue";
insertDef.Definition1="The place at which the event takes place";
Contract.Definitions.Add(insertDef);

To retrieve a value you have to type cast is back to the Definition
object as the ArrayList stores the contents in an object array.
e.g.
int index = 0;
Definition retrieveDef = (Definition)Contract.Definitions[index];

There are many methods in the ArrayList class which will help to with
the common operations such as AddRange(), ToArray(), Contains(),
etc...

Note that you have to typecast it each time you retrieve a value. This
can be overcome by inheriting from the CollectionBase class. If you
need this just mail me and i'll write a sample for you.

Hope this helps.
Prateek
 
A

Andy B

Sort of. I have to create an online contract signing system for some
customers. I also need to make it to where the admin can edit the original
contract if something changes in it. One of the sections is a Definitions
section that gives all of the words and their definitions that are used in
the contract that might not be so obvious as to what they mean. I created
the xsd schema to define the contract layout since it will be saved as an
xml file. What I have to figure out, is how to save the Definitions and
Sections lists and content. They are the only 2 "list/array" properties in
the whole Contract class. Any ideas how to make this work? These 2 sections
have to be able to support unlimited entries.

Any ideas...? I have been stuck on this for almost a week now...


CSharper said:
I have this code:

public class Contract {
private Definition[] definitionField = new Definition[];
public Definition[] Definitions {
get {return value;}
set {definitionField=value;}

}
}

Then when I go to use it like this:

//create a contract
Contract Contract = new Contract();

//assign definitions to the definitions sections. These 2 lines create:
Error 2 Array creation must have array size or array initializer
Contract.Definitions[0].Word="Venue";
Contract.Definitions[0].Definition1="The place at which the event takes
place";
...

How do you make an array without having to define the array size?

Try using ArrayList instead, by the way are you trying to build a
dictionary?
 
V

vvnraman

Sort of. I have to create an online contract signing system for some
customers. I also need to make it to where the admin can edit the original
contract if something changes in it. One of the sections is a Definitions
section that gives all of the words and their definitions that are used in
the contract that might not be so obvious as to what they mean. I created
the xsd schema to define the contract layout since it will be saved as an
xml file. What I have to figure out, is how to save the Definitions and
Sections lists and content. They are the only 2 "list/array" properties in
the whole Contract class. Any ideas how to make this work? These 2 sections
have to be able to support unlimited entries.

Any ideas...? I have been stuck on this for almost a week now...






I have this code:
public class Contract {
private Definition[] definitionField = new Definition[];
public Definition[] Definitions {
get {return value;}
set {definitionField=value;}
}
}
Then when I go to use it like this:
//create a contract
Contract Contract = new Contract();
//assign definitions to the definitions sections. These 2 lines create:
Error 2 Array creation must have array size or array initializer
Contract.Definitions[0].Word="Venue";
Contract.Definitions[0].Definition1="The place at which the event takes
place";
...
How do you make an array without having to define the array size?
Try using ArrayList instead, by the way are you trying to build a
dictionary?

Hi Andy
Don't you think that the Definitions property of the Contract class
should be indexed using the word for which the definition is required.
I think so because if you're going to have unlimited entries in the
Definitions property then finding definition for a particular word can
be very time consuming as you'll have to iterate over the array.
Anyways i'll write down the code to do this where you don't have to
type cast the object on retrieval.
Moreover, i figure out that you can have more than one definition for
a word but that is also now fixed, some word may have 2 defnitions,
some will have 5, etc. So its better that the Definition.Definition1
property should be implemented as an ArrayList i.e. a variable sized
array.

In the code below i've renamed the Definitions property of the
Contract class to ContractDictionary and the Definition.Definition1
property to WordDefinitions to remove any ambiguity. Please note that
there is still a class called Definition with two properties,
Definition.Word and Definition.WordDefinitions.

Here's the ContractDictionary class

using System;
using System.Collections;
using System.IO;
using System.ComponentModel;

namespace OnlineContractSigningSystem
{
public class ContractDictionary : DictionaryBase
{

// the object of this class contain the Definition ojbects in
a hashed
// list, hashed on the word to be defined.
// we can have an array of objects of this class to improve
the performance
// of the hashed list if it grows too large.
public ContractDictionary()
{
}

/// <summary>
/// Adds the Definition object to the hashed list if its not
already present
/// using the Add() method of the DictionaryBase class.
/// </summary>
/// <param name="newWord">Key for the hashed list.</param>
/// <param name="newElement">Definition ojbect to be used as
value</param>
/// <returns>void</returns>
public void Add(string newWord, Definition newElement)
{
if(!Dictionary.Contains(newWord)) {
Dictionary.Add(newWord, newElement);
}
else
{
// whatever you wish to do
}
}

/// <summary>
/// Removes a Definition object from the hashed list if its
present
/// using the Remove() method of the DictionaryBase class.
/// </summary>
/// <param name="oldWord">Key for the hashed list.</param>
/// <returns>void</returns>
public void Remove(string oldWord)
{
if (Dictionary.Contains(oldWord))
{
Dictionary.Remove(oldWord);
}
}
/// <summary>
/// Finds whether a word exists in the ContractDictionary or
not.
/// </summary>
/// <param name="sWord"></param>
/// <returns>bool</returns>
public bool Contains(string sWord)
{
return (Dictionary.Contains(sWord));
}

/// <summary>
/// Gets a collection of all the words.
/// </summary>
public ICollection Keys
{
get
{
return InnerHashtable.Keys;
}
}

/// <summary>
/// Gets or sets a Definition object in the hash table based
on the word
/// </summary>
/// <param name="sWord"></param>
/// <returns>Definition</returns>
public Definition this[string sWord]
{
get
{
return (Definition)Dictionary[sWord];
}
set
{
if(!Dictionary.Contains(sWord))
Dictionary[sWord] = value;
}
}


/// <summary>
/// Just to provide the foreach() statement support
/// </summary>
/// <returns>Definition</returns>
public new IEnumerator GetEnumerator()
{
foreach (object obj in Dictionary.Values)
{
yield return (Definition)obj;
}
}

}
}


Here's the WordDefinitions class

using System;
using System.Collections;

namespace OnlineContractSigningSystem
{
public class WordDefinitions : CollectionBase
{
public void Add(string newDef)
{
List.Add(newDef);
}
public void Remove(string newDef)
{
List.Remove(newDef);
}
public new void RemoveAt(int iWordDefIndex)
{
List.RemoveAt(iWordDefIndex);
}

public string this[int iWordDefIndex]
{
get
{
return (string)List[iWordDefIndex];
}
set
{
List[iWordDefIndex] = value;
}
}

}
}


Hope this helps.
I haven't compiled this yet but it shouldn't give any errors.
If you dig around the CollectionBase and the DictionaryBase from the
MSDN, you'll find out various methods to add the these classes.

Prateek.
 
V

vvnraman

Sort of. I have to create an online contract signing system for some
customers. I also need to make it to where the admin can edit the original
contract if something changes in it. One of the sections is a Definitions
section that gives all of the words and their definitions that are used in
the contract that might not be so obvious as to what they mean. I created
the xsd schema to define the contract layout since it will be saved as an
xml file. What I have to figure out, is how to save the Definitions and
Sections lists and content. They are the only 2 "list/array" properties in
the whole Contract class. Any ideas how to make this work? These 2 sections
have to be able to support unlimited entries.
Any ideas...? I have been stuck on this for almost a week now...
news:09ce40ed-8be9-454f-a7cb-0202f74208e7@x41g2000hsb.googlegroups.com...
I have this code:
public class Contract {
private Definition[] definitionField = new Definition[];
public Definition[] Definitions {
get {return value;}
set {definitionField=value;}
}
}
Then when I go to use it like this:
//create a contract
Contract Contract = new Contract();
//assign definitions to the definitions sections. These 2 lines create:
Error 2 Array creation must have array size or array initializer
Contract.Definitions[0].Word="Venue";
Contract.Definitions[0].Definition1="The place at which the event takes
place";
...
How do you make an array without having to define the array size?
Try using ArrayList instead, by the way are you trying to build a
dictionary?

Hi Andy
Don't you think that the Definitions property of the Contract class
should be indexed using the word for which the definition is required.
I think so because if you're going to have unlimited entries in the
Definitions property then finding definition for a particular word can
be very time consuming as you'll have to iterate over the array.
Anyways i'll write down the code to do this where you don't have to
type cast the object on retrieval.
Moreover, i figure out that you can have more than one definition for
a word but that is also now fixed, some word may have 2 defnitions,
some will have 5, etc. So its better that the Definition.Definition1
property should be implemented as an ArrayList i.e. a variable sized
array.

In the code below i've renamed the Definitions property of the
Contract class to ContractDictionary and the Definition.Definition1
property to WordDefinitions to remove any ambiguity. Please note that
there is still a class called Definition with two properties,
Definition.Word and Definition.WordDefinitions.

Here's the ContractDictionary class

using System;
using System.Collections;
using System.IO;
using System.ComponentModel;

namespace OnlineContractSigningSystem
{
public class ContractDictionary : DictionaryBase
{

// the object of this class contain the Definition ojbects in
a hashed
// list, hashed on the word to be defined.
// we can have an array of objects of this class to improve
the performance
// of the hashed list if it grows too large.
public ContractDictionary()
{
}

/// <summary>
/// Adds the Definition object to the hashed list if its not
already present
/// using the Add() method of the DictionaryBase class.
/// </summary>
/// <param name="newWord">Key for the hashed list.</param>
/// <param name="newElement">Definition ojbect to be used as
value</param>
/// <returns>void</returns>
public void Add(string newWord, Definition newElement)
{
if(!Dictionary.Contains(newWord)) {
Dictionary.Add(newWord, newElement);
}
else
{
// whatever you wish to do
}
}

/// <summary>
/// Removes a Definition object from the hashed list if its
present
/// using the Remove() method of the DictionaryBase class.
/// </summary>
/// <param name="oldWord">Key for the hashed list.</param>
/// <returns>void</returns>
public void Remove(string oldWord)
{
if (Dictionary.Contains(oldWord))
{
Dictionary.Remove(oldWord);
}
}
/// <summary>
/// Finds whether a word exists in the ContractDictionary or
not.
/// </summary>
/// <param name="sWord"></param>
/// <returns>bool</returns>
public bool Contains(string sWord)
{
return (Dictionary.Contains(sWord));
}

/// <summary>
/// Gets a collection of all the words.
/// </summary>
public ICollection Keys
{
get
{
return InnerHashtable.Keys;
}
}

/// <summary>
/// Gets or sets a Definition object in the hash table based
on the word
/// </summary>
/// <param name="sWord"></param>
/// <returns>Definition</returns>
public Definition this[string sWord]
{
get
{
return (Definition)Dictionary[sWord];
}
set
{
if(!Dictionary.Contains(sWord))
Dictionary[sWord] = value;
}
}

/// <summary>
/// Just to provide the foreach() statement support
/// </summary>
/// <returns>Definition</returns>
public new IEnumerator GetEnumerator()
{
foreach (object obj in Dictionary.Values)
{
yield return (Definition)obj;
}
}

}

}

Here's the WordDefinitions class

using System;
using System.Collections;

namespace OnlineContractSigningSystem
{
public class WordDefinitions : CollectionBase
{
public void Add(string newDef)
{
List.Add(newDef);
}
public void Remove(string newDef)
{
List.Remove(newDef);
}
public new void RemoveAt(int iWordDefIndex)
{
List.RemoveAt(iWordDefIndex);
}

public string this[int iWordDefIndex]
{
get
{
return (string)List[iWordDefIndex];
}
set
{
List[iWordDefIndex] = value;
}
}

}

}

Hope this helps.
I haven't compiled this yet but it shouldn't give any errors.
If you dig around the CollectionBase and the DictionaryBase from the
MSDN, you'll find out various methods to add the these classes.

Prateek.

Ah, I forgot to tell you how to use this using your original code.
It follows here
public class Contract
{
private ContractDictionary contractDict = new ContractDictionary();
public ContractDictionary ContractDictionary
{
get {return value;}
set {contractDict=value;}
}
}

public class Definition
{
private string word = "";
public string Word
{
get {return value;}
set {word = value;}
}
private WordDefinitions wordDefs = new WordDefinitions();
public WordDefinitions WordDefinitions
{
get {return value;}
set {wordDefs = value;}
}
}

//create a contract
Contract Contract = new Contract();

//create a definition
Definition newDef = new Definition();
newDef.Word = "Venue";
newDef.WordDefinitions.Add("The place at which the event takes
place");
newDef.WordDefinitions.Add("Meeting place");

//add the definition to the ContractDictionary

Contract.ContractDefinitions.Add(newDef.Word, newDef);

// To retrieve the Definition
if(Contract.ContractDictionary.Contains("Venue"))
{
Definition def = Contract.ContractDictionary["Venue"];
}

// You can add new definitions as easily as
Contract.ContractDictionary["Venue"].WordDefinitions.Add("O local onde
o evento ocorre"); // spanish for the first def.

Regards
Prateek
 
E

Eps

Andy said:
Unless I'm wrong, the last I heard was that <list t> couldn't be serialized
into an xml file. It is required that the contract objects be stored inside
of xml files of some form or another (unless there are other ideas I don't
know about). is there any way to fix this?

depends which version of .net you are using, the latest, 3.5, can
serialize List<T> to xml objects fine.
 
A

Andy B

It's .net 2.0 because I am using web application projects that require
compilation. I can't get vs 2008 standard+ right now so am kind of stuck.
 
F

Family Tree Mike

Lists serialize just fine in 2.0. Are you thinking of Dictionary<,> objects?
They don't serialize.
 
A

Andy B

Actually I was looking at something like:
using System.Collections.Generic;
....

public class Contract {
//private fields.
private List<DictionaryEntry> _definitions = new List<DictionaryEntry>();

//public properties
public list<DictionaryEntry> Dictionary {
get {return _definitions;}
set { _definitions = value; }
}
....
}
Where <DictionaryEntry> is a custom built data type that defines what a
DictionaryEntry would look like. Below would be the DictionaryEntry data
type:

public class DictionaryEntry {
private string _word;
private string _definition;

[System.Xml.Serialization.XmlAttributeAttribute()]

public string Definition {
get { return _definition; }
set { _definition = value; }
}

[System.Xml.Serialization.XmlAttributeAttribute()]

public string Word {
get { return _word; }
set { _word = value; }
}
}

Then I can do something like:

Contract Contract = new Contract();

DictionaryEntry Venue = new DictionaryEntry();
Venue.Word="Venue";
Venue.Definition="The place where the event will take place";

Contract.Dictionary.Add(Venue);

....

Or would I be way off base with this?
 
F

Family Tree Mike

That looks like it would work (I didn't try it). But if you want a
serializable dictionary, I used the code at this link once. It seemed to
work well.

http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx


Andy B said:
Actually I was looking at something like:
using System.Collections.Generic;
....

public class Contract {
//private fields.
private List<DictionaryEntry> _definitions = new List<DictionaryEntry>();

//public properties
public list<DictionaryEntry> Dictionary {
get {return _definitions;}
set { _definitions = value; }
}
....
}
Where <DictionaryEntry> is a custom built data type that defines what a
DictionaryEntry would look like. Below would be the DictionaryEntry data
type:

public class DictionaryEntry {
private string _word;
private string _definition;

[System.Xml.Serialization.XmlAttributeAttribute()]

public string Definition {
get { return _definition; }
set { _definition = value; }
}

[System.Xml.Serialization.XmlAttributeAttribute()]

public string Word {
get { return _word; }
set { _word = value; }
}
}

Then I can do something like:

Contract Contract = new Contract();

DictionaryEntry Venue = new DictionaryEntry();
Venue.Word="Venue";
Venue.Definition="The place where the event will take place";

Contract.Dictionary.Add(Venue);

....

Or would I be way off base with this?


Family Tree Mike said:
Lists serialize just fine in 2.0. Are you thinking of Dictionary<,>
objects?
They don't serialize.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top