what does out in **out string [][] teams** mean - c#

what does out mean in a multidimensional param, if it's possible write an eg please, I'll really appreciate
public string GetTeamsInfo(out string[][] teams)
{
...
}

out means the parameter is an {out}put parameter
opposed to the default input parameter (note: an input parameter is not the same as a parameter using the in modifier, that is an input only parameter and imposes it own requirements)
this means it has no value at the beginning of the function and you need to assign one for it to be passed back to the calling code
see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
public string GetTeamsInfo(out string[][] teams)
{
teams = new string[3][4];
return "test";
}
string[][] teams;
//here teams is null
string text = GetTeamsInfo(out teams);
//here teams is a array of string[]

Related

Strange? issue with cast of List<T> to array

I've defined List
private class Kamery
{
public int iIndeks;
public string strNazwa;
public Kamery(int Indeks, string Nazwa)
{
iIndeks = Indeks;
strNazwa = Nazwa;
}
}
List<Kamery> lKamery = new List<Kamery>();
I'd like to cast searched list of names to string array like:
string[] strNazwa = (string)lKamery.Find(item => item.iIndeks == iIndeks).strNazwa.ToArray();
But compiler says Cannot convert type 'char[]' to 'string'
Why? How it needs to be done?
I think you want:
string[] strNazwa = lKamery.Where(item => item.iIndeks == iIndeks)
.Select(item => item.strNazwa)
.ToArray();
That will give you a string array that contains each of the strNazwa values from the list for items that meet the Where condition.
Here's what your original code was doing:
string[] strNazwa = (string)
// get the one item that matches the condition
lKamery.Find(item => item.iIndeks ==Indeks)
// get the strNazwa property from that one item
.strNazwa
// return the string as a char array
.ToArray();
When you try to cast the char[] to a string it fails since you can't cast it. You can create a string from a character array but not via a cast.
I think your problem is that .Find returns only 1 value , the first match in the list.
https://msdn.microsoft.com/en-us/library/x0b5b5bc(v=vs.110).aspx
This value will be a string and by using .toArray , you are converting that string to a char[ ] and then trying to cast it back to string.
I'm not that good at c# , so the generic solution would be:
Declare the array, do a foreach and every time the id matches put the name into the array and inc the index. This limits it somewhat as you have to have a fixed size, would probably be better to use List instead.

Returning the new string in the method

I'm newbie to c#, So i tried the below program, which will change the case of the first character of the string
public class StringBuilder
{
public static string ChangeFirstLetterCase(string inputdata)
{
if(inputdata.Length > 0)
{
char[] charArray = inputdata.ToCharArray();
charArray[0] = char.IsUpper(charArray[0]) ?
char.ToLower(charArray[0]) : char.ToUpper(charArray[0]);
//return new string(charArray);
return charArray.ToString();
}
return inputdata;
}
}
class Program
{
static void Main(string[] args)
{
var a = StringBuilder.ChangeFirstLetterCase("vishnu");
Console.WriteLine(a);
Console.ReadLine();
}
}
Since the return type of this method ChangeFirstLetterCase() is a string. So I'm just doing the conversion like below
`return charArray.ToString();`
So in the method call it is returning the System.Char[]
Alternatively I tried the below one as well
`return new string(charArray);`
So this is returning the value as expected
Argument to the method - "vishnu"
Return value - "Vishnu"
So my question here is
Since the return type of the method is string, what's wrong with below conversion?
return charArray.ToString();
How do we know when to return as new string?.
return new string(charArray);
Please provide me some example
If you return the char array as a String, it will return you the name of the object System.Char[]. This is because the ToString method of char arrays does not build the characters of the array into a usable string, but simply makes a String that states the type of object.
However, if you use new String(char[]), this will read the contents of the char array to build a string out of whatever characters are in the char array. So, you will want to use new String(char[]) for most of your String building, I cannot think of any real uses for using the ToString() on a char array.
So, for your example, you should use return new String(charArray); instead of return charArray.ToString();.
charArray.ToString(); returns the type name because it's implemented that way, for getting string back from a character array you will always have to use String class constructor.
ToString method for char[] is not implemented in a way to return the character array back as a string literal, so use String constructor as you did in the second case.
You could return:
if(inputData[0].IsLower())
return string.Concat(inputData[0].ToUpper(), inputData.Substring(1));
else
return string.Concat(inputData[0].ToLower(), inputData.Substring(1));
Your value would already be a usable string and wouldn't need to have a char[].
I'm not really sure what you gain from converting the string to a char array to being with.

Converting a double list into a string

I have an array of double which I am sending via JSON to my aspx page.
var array = [] //this array is having double values in it. (48.154176701412744,11.551694869995117),(48.15131361676726,11.551694869995117),(48.15555092529958,11.549291610717773)
var jsonText = JSON.stringify({ list: array });
And following is the method I am passing it to:
public static void Demo(double[] list)
Now how can I access the array being sent and convert it into a string so that I can save it into my database column as string? Because when I accept it as
public static void Demo(string[] list)
It doesn't even accept the JSON object. And when I make the method as:
public static void Demo(double[] list)
It takes the array as [0 0 0].
You can join all doubles with some delimiter:
string.Join(";", list);
However, you should pay attention to using decimal separator. If value will be saved as 1.52;0.4, later you can fail on another machine, or if locale will be changed. I'd decide, what separator I will use always for this case and will convert values to string and back with this separator:
// unfortunately, not tested
var ni = NumberFormatInfo.CurrentInfo; // not sure if you better call Clone() here
ni.NumberDecimalSeparator = ".";
string todatabase = string.Join(";", list.Select(_ => _.ToString(ni)));
To do the opposite operation:
// unfortunately, not tested
var ni = NumberFormatInfo.CurrentInfo; // not sure if you better call Clone() here
ni.NumberDecimalSeparator = ".";
// `str` is read from database value
IEnumerable<double> fromdatabase = str.Split(';').Select(_ => double.Parse(_, ni));
Pay attention to errors handling, this code fragments will fail on bad values (e.g. list was null, str was null, str was containing not-convertible to double values, etc)
JSON.stringfy is itself return a string then why do you need to convert the values to string.You can use JSON.parse('#Html.Raw(jsonText)') to parse the json string on aspx page.This json string can be passed using Session variable.

Convert a String[] into an object and back into a String[]?

I'm putting a concatenated string into the Tag property of a component this way:
Tag = String.Format("{0};{1};{2}", AThis, AThat, ATheOtherThing);
Now how do I get it out, as Tag is an object? Trying to do this:
String[] someStuff = Tag.Split(';');
I get, "'object' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'object' could be found
The type of Tag is object but the Split method is on String. You need to cast Tag back to String in order to call Split
string[] someStuff = ((string)Tag).Split(';');
As object can be cast to and from any other data type, you can skip the string.Format() completely, and assign a string[]
Tag = new string[] { AThis, AThat, ATheOtherThing };
and
string[] someStuff = (string[])Tag;
or use object[] if AThis, AThat, ATheOtherThing are different data types.
Unless you have some driving need for it as a string another way would be a struct that held your three values, then just set tag to it, and to get it back cast it. No more formating and splitting then. More importantly if you add a fourth item, refactor the struct, job done.
A safe way to convert the Tag back to string is to use the as keyword. If the Tag contains something else than a string it does not throw an exception but returns null
string s = Tag as string;
string[] someStuff = null;
if (s != null) {
someStuff = s.Split(';');
}

How is String.Format method treated?

As is described at Microsoft Site ,String.Format arranges some String Variables into a single String and is another way how to concate string's in c#.
string.Format("Name = {0} Surname = {1}",name,surname);
My question is how does this work ?
Is this method a Special method ,and can i create a method similar to this one which accepts at every {n} only an Integer .
Or is this method interpreted in a different way by compiler ,if yes than how does the compiler accesses this method .
If it's possible i would like to see ,how does the compiler interpret this Method.
PS : How does it work ,when you can send as much parameters as you want to a method ?
[EDIT]
Does it mean ,that String.Format takes the first Parameter and filter's into with a Regex or Whatever tool (Split etc) to get where {Number} is and places there a String token from second params portion ?
Sending a variable number of parameters to a method is done like this:
public static string MyStringFormat(string formatString, params object [] args)
{
}
You can now pass as many parameters as you like to this:
MyStringFormat("{0}{1}",42,"Hello World")
MyStringFormat("{0}{1}{2}",42,"Hello World",999.9)
Within the method, these arguments are simply an array (of object in this case).
here are the docs on the params keyword.
As for writing you own method to accept numeric input like Format does, this would be one way (using regular expressions):
public static string MyStringFormat(string formatString, params object[] args)
{
var regex = new Regex("{([0-9]*)}");
return regex.Replace(formatString,m =>
{
int index = int.Parse(m.Groups[1].Value);
if(index<args.Length)
return args[index].ToString();
return String.Empty;
});
}
Live example: http://rextester.com/rundotnet?code=OMZC13551
It is a normal function.
It parses the string and calls ToString on the incoming parameters (if needed) in order to construct the new string.
The signature of the overload you have in your example is:
public static string Format(
string format,
params Object[] args
)
There is nothing to stop you from creating your own (though I would probably just delegate to the built in string.Format).
Use params: http://msdn.microsoft.com/en-us/library/w5zay9db.aspx
there is no magic there Cody, look at this method:
public static void UseParams(params int[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
you can call it passing as many int you like, it's the params parameter type :)
Edit:
params is very useful it allows us, for example, to pass to our logging wrapper all method's parameters values in a dynamic way without knowing how many of them each method has, the logger will then dump all those values one by one using Reflection to find out the parameter name as well.
The braces in the string are placeholders and a number within that denotes the index of argument it is to be replaced with.
Format is of type (string format, params object[] args) and it is the index in this object[] which is helpful.
(I think it internally uses the StringBuilder.AppendFormat) for substituting those values)
The signature of String.Format looks like this:
public static string Format (string format, params Object[] args)
Note the second parameter, marked with the params keyword. That one provides the functionality to add multiple parameters when calling the function. Inside the function you can access the parameters by index or iterating over args array:
public static string Format (string format, params Object[] args)
{
foreach (Object o in args)
Console.WriteLine(o);
}
Have a look at the C# Reference.

Categories