In C#, the array can be initialized by the following syntax
string[]arr = {"text1","text2"}; // this works
why does the following not work
string[]arr1;
arr1={"phrase1","phrase2"};//Does not compile.
string[] arr = { "text1", "text2" };
This works because this is a special syntax only allowed when first initializing an array variable (personally I didn't even know it existed).
If you want to later assign a new array to a variable, you need to say new:
arr = new string[] { "text1", "text2" };
You can also say just new [] and the compiler will figure out the type for you.
The second syntax is wrong according to the C# specification:
http://msdn.microsoft.com/en-us/library/aa664573%28v=vs.71%29.aspx
Check that link as well for more examples about how to initialize an array:
All possible C# array initialization syntaxes
It's all about allocating memory.
The first is short for:
string[]arr = new string[]{"text1","text2"};
So the compiler knows in the same statement the number of elements to allocate using the new keyword.
The second is just wrong syntax.
If you want to do it in two steps:
string[]arr1; // defines array(pointer)
arr1=new string[]{"phrase1","phrase2"}; // again when `new` is used for dynamic memory allocation, the size is available.
Related
I'm trying to make a sorting algorithm and asking the user to input the array size is a must. I am a beginner in C# so I don't have any idea how to do that.
This is the idea that came to my mind, but I'm having an error.
Console.WriteLine("Enter how many elements you want to be sorted:");
a = Convert.ToInt32(Console.ReadLine());
int[] MyArray= new int[a] {""};
Visual Studio says that 'a constant value is expected'. How could I make the array length a ReadLine? My goal is for the user to decide which array length they want the program to show and that the elements inside the array would be system generated based on the array length that the user chose.
You can initialise an array like this:
int[] MyArray= new int[a];
But, I would also point out, that you could use a dynamic collection (such as a list), then you don't need to ask up front how many items, you just keep adding items until the user decides to stop.
ICollection<int> myCollection = new List<int>();
myCollection.Add(1);
myCollection.Add(1);
The type of your array is int but you are trying to initialize it with an empty string. In C# you can declare an array in a few ways. You can declare it by providing a size as in:
int[] myArray = new int[size];
And initialize the values later.
An alternative is to instantly intialize it with values like this:
int[] myArray = new int[] { 1, 2, 3 };
Note that when using the second option, you shouldn't provied the size as the compiler will infere it.
I am currently studying computing at UCLAN and I have to write a program using Spec# and I need a 2 dimensial jagged array which can not be null.
I know for a normal array I can declare it like this
T![]!
but when i want to declare it for a jagged array I should write it somehow like this
T![]![]
This works pretty well but when I want to init it:
T![]![] = new T![365]![]
it throws an error and I just can't find how to get this fixed.
I did not find out how I can init the array correctly but I found a workaround.
T![]![]! = (T![]![]) new T![][];
This is how it works!
HOMEWORK: I'm getting and index out-of-bounds on the following code. It's a hangman game, and I'm keeping track of the letters I've guessed in a char array.
Here's the assumptions I made:
In the calling method, I have an unpopulated array (char[] displayGuesses = new char[26];) passing to the method below as the char[] usedLetters parameter.
The first iteration of the letter-guessing, the array will be empty.
It's length will be 0.
I populate usedLetters[0] with the letterGuessed parameter.
The next time I guess, length of the array will be 1, so usedLetters[1] gets populated...and so on.
public char[] trackUsedLetters(char letterGuessed, char[] usedLetters)
{
int letterIndex = usedLetters.Length;
usedLetters[letterIndex] = letterGuessed;
return usedLetters;
}
There's a couple things I think may be going on.
When I try to get the length of usedLetters on the first run, the empty array does
NOT return zero, but null. Boom. Out-of-bounds.
There's some issue with passing a blank array defined with 26
members...? But I'm not sure what that issue would even BE, so I have no idea what to google that will yield relevant results.
I may have a scope issue; I found this link to a similar
question for Java, though using a for loop. I don't quite get
what the Java user was going for, but some of the problems sounded
familiar.
I need a second pair of eyes to look at this and point me in the right direction for solving this.
According to the c# specification: (emphasis mine)
1.8 Arrays
Array types are reference types, and the declaration of an array variable simply sets aside space for a reference to an array instance. Actual array instances are created dynamically at run-time using the new operator. The new operation specifies the length of the new array instance, which is then fixed for the lifetime of the instance. The indices of the elements of an array range from 0 to Length - 1. The new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types.
Default Values which gives the char data type default as '\0'
It looks like you want List<char> that can grow (with Add) method.
Arrays have fixed size and following code (that you have in sample) will always throw out of range exception because you are accessing element past last element in array.
usedLetters[usedLetters.Length] = 'c';
More details on array length:
// newArray - array of 0 chars. newArray.Length is 0
var newArray = new char[0];
// nullArray not created, nullArray.Length will throw NullReferenceExcetption
char[] nullArray = null;
// defaultArray = array of 26 characters, each value 0.
// defaultArray.Length is 26;
char[] defaultArray = new char[26];
When you define a new array, but don't manually initialize the items inside of it, it will automatically be initialized with the default values for whatever type the array contains. In your case, you're creating a character array. The default value for a char is '\0', or the null character.
This means that the array is never truly "empty." If you define an array with 26 slots, it will always have that length, unless you make a new array.
I want to convert IList to array:
Please see my code:
IList list = new ArrayList();
list.Add(1);
Array array = new Array[list.Count];
list.CopyTo(array, 0);
Why I get System.InvalidCastException : At least one element in the source array could not be cast down to the destination array type? How that can be resolved assuming I can not use ArrayList as type for list variable ?
Update 1: I use .NET 1.1. So I can not use Generics, Linq and so on. I just want to receive result for the most common case - integer was given as example, I need this code works for all types so I use Array here (maybe I am wrong about using Array but I need, once again, common case).
You're creating an array of Array values. 1 is an int, not an Array. You should have:
IList list = new ArrayList();
list.Add(1);
Array array = new int[list.Count];
list.CopyTo(array, 0);
or, ideally, don't use the non-generic types to start with... use List instead of ArrayList, IList<T> instead of IList etc.
EDIT: Note that the third line could easily be:
Array array = new object[list.Count];
instead.
You can use Cast and ToArray:
Array array = list.Cast<int>().ToArray();
I'm surprised that
Array array = new Array[list.Count];
even compiles but it does not do what you want it to. Use
object[] array = new object[list.Count];
And, standard remark: if you can use C#3 or later, avoid ArrayList as much as possible. You'll probably be happier with a List<int>
probably the most compact solution is this:
Enumerable.Range(0, list.Count).Select(i => list[i]).ToArray();
I have two arrays of strings:
string[] all = new string[]{"a", "b", "c", "d"}
string[] taken = new string[]{"a", "b"}
I want to generate a new string array with c and d which is all - taken.
Any quick way in .net 3.5 to do this without a manual loop and creating new lists?
var remains = all.Except(taken);
Note that this does not return an array. But you need to ask yourself if you really need an array or if IEnumerable is more appropriate (hint: it almost always is). If you really need an array, you can just call .ToArray() to get it.
In this case, there may be a big performance advantage to not using an array right away. Consider you have "a" through "d" in your "all" collection, and "a" and "b" in your "taken" collection. At this point, the "remains" variable doesn't contain any data yet. Instead, it's an object that knows how to tell you what data will be there when you ask it. If you never actually need that variable, you never did any work to calculate what items belong in it.
You are using LINQ Except for it, like all.Except(taken).
string[] result = all.Except<string>(taken).ToArray<string>();