I want to declare a function that has 1 required argument and 4 optional 2D array arguments, how do i do so? I know to make an argument optional, we should place a value in it during function creation.
I also saw what I did below is wrong and has a "Array initializers can only be used in a variable or field initializer. Try using a new expression instead." Error
private String communicateToServer(String serverHostname,
String[,] disk = new string[] {{"dummy","dummy"}},
String[,] hdd= new string[] {{"dummy","dummy"}}
String[,] nic= new string[] {{"dummy","dummy"}}
String[,] disk = new string[] {{"dummy","dummy"}}
)
It's not possible to do this directly but you can get a similar effect by doing the following pattern
private String communicateToServer(String serverHostname,
String[,] disk = null,
String[,] hdd= null,
String[,] nic= null) {
disk = disk ?? new string[] {{"dummy","dummy"}},
hdd= hdd ?? new string[] {{"dummy","dummy"}}
nic= nic ?? new string[] {{"dummy","dummy"}}
...
}
Essentially use null as the default and if null is the value convert to the actual default. This does mean that an explicit null being passed will be interpreted as the default value though.
Related
I've seen All possible C# array initialization syntaxes which shows several different ways to initialize an array.
Does the following initialization creates an instance that is different in some ways compared to one created with regular call with new ?
Initialization:
string[] strArray = {"one","two","three"};
Compared to string[] strArray = new String[] {"one","two","three"};
It is a syntactic sugar. The compiler transforms this:
string[] strArray = {"one","two","three"};
To This:
string[] expr_07 = new string[] {
"one",
"two",
"three"
};
Above output is using Roslyn C# compiler.
You can't initialize something that's not there. So yes, a new instance does get created, in the exact same way as though you had written the new operator. It's just a convenience provided by the language for when you're initializing an array at the same time that you're declaring it so you aren't forced to write it out (when doing it in a separate statement, the new operator is required because the compiler can't assume you haven't already assigned an array reference to the variable beforehand — the very bare minimum you can get away with in a separate statement is strArray = new[] {...};).
This could be very easy, but how can I place or convert a string into an array?
The code that I have, is the following:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string one;
string[] two;
one = "Juan";
two = {one}; // here is the error
HttpContext.Current.Response.Write(two);
}
}
And the error is the following:
Compiler Error Message: CS0029: Cannot implicitly convert type 'string' to 'string[]'
Thanks for you help!
Replace this:
two = {one}; // here is the error
With
two = new[] { one };
OR
two = new string[] { one };
The reason you are getting the error is clear from the error message.
See: Object and Collection Initializers (C# Programming Guide)
Later when you are doing Response.Write, you will get System.String[] as output, since two is an array. I guess you need all array elements separated by some delimiter. You can try:
HttpContext.Current.Response.Write(string.Join(",", two));
Which will produce all the elements in the array separated by comma
It looks like you're trying to use initialization syntax for an assignment. This should work:
two = new string[] {one};
or just
two = new [] {one};
since the compiler will infer that you want a string[]
I think you'll also be surprised what Response.Write(two); produces...
You're using the static initializer syntax to try and add an item to your array. That doesn't work. You can use similar syntax to allocate a new array with the value one - two = new string[] { one }; - or you can allocate the array then add elements through assignment like;
string[] two = new string[10];
two[0] = one; // assign value one to index 0
If you do it like this you have to do some bounds checking for example the following will throw an IndexOutOfRangeException at runtime;
string[] two = new string[10];
int x = 12;
two[x] = one; // index out of range, must ensure x < two.Length before trying to assign to two[x]
That syntax ({one}) is only valid if you declare the array variable in the same line. So, this works:
string one;
one = "Juan";
string[] two = {one};
A more common way to initialize an array, which works in more places, is to use the new keyword, and optionally have the type be inferred, e.g.
string one;
string[] two;
one = "Juan";
// type is inferrable, since the compiler knows one is a string
two = new[] {one};
// or, explicitly specify the type
two = new string[] {one};
I usually declare and initialize on the same line, and use var to infer the type, so I'd probably write:
var one = "Juan";
var two = new[] { one };
var movieNext = new string[,]
{
{ "superhero", "action", "waltdisney", "bat"},
{"superhero", "action", "marvel",""},
{"history", "action", "malay", "" },
{"malay", "novel", "", ""},
{"history", "bat", "", ""}
};
The above code is a multidimensional array, which stores a sequence of movie's keyword. Is there a way to implement this without having to put the blank strings in the array initialization?
For example you can see in the above code, I have to put the blank string "" to fill up the array.
You could use a jagged array instead.
string[][] movieNext = new string[][] { { etc... } }.
You can consider C# jagged array (though they are different from multi-dimensional arrays).
string[][] movieNext = {
new [] { "superhero", "action", "waltdisney", "bat"},
new [] {"superhero", "action", "marvel"}, <and so on>
};
If you want to stick with multi-dimensional arrays, you have to initialize the values individually. If you don't provide any string value for any of the index (i,j) by default it will be null.
I suggest never to use two-dimensional arrays. They have practically no support in the API (you'll be hard pressed to find a method that accepts a two-dimensional array as a parameter), and cannot be cast to IEnumerable<T> or similar well-supported interface. As such, you can really use them only in the most local of scopes.
Instead, I suggest you use something castable to IEnumerable<IEnumerable<string>>. Oh, another tip. Check this out. Specifically,
To initialize a Dictionary, or any collection whose Add method takes multiple parameters, enclose each set of parameters in braces as shown in the following example.
Thus, the following will work:
class Program
{
static void Main(string[] args)
{
var d = new ManyList()
{
{"Hi", "Good", "People", "None", "Other"}
{"Maybe", "Someone", "Else", "Whatever"}
};
Console.Read();
}
}
class ManyList : List<string>
{
public void Add(params string[] strs)
{
Console.WriteLine(string.Join(", ", strs));
}
}
This might help you clean up your syntax a bit.
Without initialization how is it possible to assign values to arrays?
string[] s={"all","in","all"};
I mean why did not the compile show error?.Normally we need to
initialize ,before assign values.
It's just syntactic sugar.
This:
string[] s = {"all","in","all"};
is compiled to the same code as:
string[] tmp = new string[3];
tmp[0] = "all";
tmp[1] = "in";
tmp[2] = "all";
string[] s = tmp;
Note that the array reference is not assigned to s until all the elements have been assigned. That isn't important in this particular case where we're declaring a new variable, but it would make a different in this situation:
string[] s = { "first", "second" };
s = new string[] { s[1], s[0] };
The same is true for object and collection initializers - the variable is only assigned at the end.
It is possible to declare an array variable without initialization.
Check this out
http://msdn.microsoft.com/en-us/library/0a7fscd0%28VS.71%29.aspx
You aren't "assigning a value to array". You are initializing a variable of type "reference to array". The value with which you initialize it is a reference to an array which was created by the use of short array initializer syntax {...}. While it is only permissible in initializer of variables of array type, it is exactly equivalent to new T[] { ... }, where T is deduced from type of variable.
I think you want to know why
string[] s={"all","in","all"};
works when you would expect to be required to initialize the array first like this :
string[] s = new string[];
or
string[] s = new string[] {"all","in","all"};
The answer is just compiler magic. The compiler knows based on the initialization how big to make the array so it just does it behind the scenes for you. Much like the var keyword, the point is to limit the amount of redundant information you're required to type.
The {"all","in","all"} part is the initialization. the new string[] part can be omitted because the curly braces and string are short hand notation. Take a look at MSDN on Single Dimension Arrays.
string[] s = new string[] { "all","in","all"};
and its shorthand version
string[] s = {"all","in","all"};
are the same thing. See MSDN (Initializing Arrays section) for more detail.
You don't need the new string[] part in C#3 or higher - this works fine
string[] s = { "all","in","all"};
It's just a case of the compiler being a bit smarter and working out what you mean - the back end IL will be the same.
You can do so simply because it is allowed, doing so in two steps is not necessary so this is the shorthand. Consider it sugar.
How is an array of string where you do not know where the array size in c#.NET?
String[] array = new String[]; // this does not work
Is there a specific reason why you need to use an array? If you don't know the size before hand you might want to use List<String>
List<String> list = new List<String>();
list.Add("Hello");
list.Add("world");
list.Add("!");
Console.WriteLine(list[2]);
Will give you an output of
!
MSDN - List(T) for more information
You don't have to specify the size of an array when you instantiate it.
You can still declare the array and instantiate it later. For instance:
string[] myArray;
...
myArray = new string[size];
You can't create an array without a size. You'd need to use a list for that.
you can declare an empty array like below
String[] arr = new String[]{}; // declare an empty array
String[] arr2 = {"A", "B"}; // declare and assign values to an array
arr = arr2; // assign valued array to empty array
you can't assign values to above empty array like below
arr[0] = "A"; // you can't do this
As others have mentioned you can use a List<String> (which I agree would be a better choice). In the event that you need the String[] (to pass to an existing method that requires it for instance) you can always retrieve an array from the list (which is a copy of the List<T>'s inner array) like this:
String[] s = yourListOfString.ToArray();
I think you may be looking for the StringBuilder class. If not, then the generic List class in string form:
List<string> myStringList = new List<string();
myStringList.Add("Test 1");
myStringList.Add("Test 2");
Or, if you need to be absolutely sure that the strings remain in order:
Queue<string> myStringInOriginalOrder = new Queue<string();
myStringInOriginalOrder.Enqueue("Testing...");
myStringInOriginalOrder.Enqueue("1...");
myStringInOriginalOrder.Enqueue("2...");
myStringInOriginalOrder.Enqueue("3...");
Remember, with the List class, the order of the items is an implementation detail and you are not guaranteed that they will stay in the same order you put them in.
I suppose that the array size if a computed value.
int size = ComputeArraySize();
// Then
String[] array = new String[size];
Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?
If you will later know the length of the array you can create the initial array like this:
String[] array;
And later when you know the length you can finish initializing it like this
array = new String[42];
If you want to use array without knowing the size first you have to declare it and later you can instantiate it like
string[] myArray;
...
...
myArray=new string[someItems.count];
string[ ] array = {};
// it is not null instead it is empty.
string foo = "Apple, Plum, Cherry";
string[] myArr = null;
myArr = foo.Split(',');