Why am I getting System.char[] printed out in this case? - c#

I'm trying to figure out what I'm doing wrong here, but I can't seem to. I have this method that takes in a string and reverses it. However, when I print out the reversed string from the caller method, I just get "System.Char []" instead of the actual reversed string.
static string reverseString(string toReverse)
{
char[] reversedString = toReverse.ToCharArray();
Array.Reverse(reversedString);
return reversedString.ToString();
}

Calling ToString on a T array in .NET will always return "T[]". You want to use this instead: new string(reversedString).

By calling ToString you just get the default implementation that every class inherits from object. .NET can't provide a special implementation just for an array of char; the override would have to apply to all types of array.
Instead, you can pass the array to String's constructor, return new String(reversedString).

Related

Why is "System.Byte[]" coming when "byte[]" is entered?

I'm a beginner to programming and use C# to learn programming. When I enter this code
byte[] bytes={1,2,3};
Console.WriteLine(bytes);
the output isSystem.Byte[].
Why is that? How can I fix it?
foreach (byte b in bytes)
{
Console.WriteLine(b);
}
iteration - the repetition of a process or utterance.
As per the removed comment on your post, you need to iterate over each byte to get the value. As it is, you're simply printing out the type when you try and print an array and not it's elements.
byte[] bytes = { 1, 2, 3 };
foreach(byte b in bytes)
{
Console.Write(b);
}
I think that #Aquaballin beat me to the punch; we even use a similar method of iterating! :D
The console is writing out the string value of the byte array, which is "System.Byte[]".
You need to print out each item in the Byte array individually, which is most simply done like this:
foreach(Byte item in bytes)
{
Console.WriteLine(item));
}
Console.WriteLine generally expects a string. If the value or object passed in as parameter is of a different time it will convert the value or object internally to a string by calling its .ToString() method. The .ToString method of any array type will only return the type name, not its content. You presumably want to print out the content of the array. #Aquaballin's answer is almost what you tried to accomplish, except for the superfluous line breaks. I'll also add some commas as delimiters.
foreach (byte b in bytes)
{
Console.Write(b);
}
Console.WriteLine();
Console.WriteLine(obj) implicitly calls the ToString method on the passed parameter. In the case of a System.Byte[] (aka: byte[]) type, the ToString method is implemented ultimately by the System.Object base class. The code for that method (via ILSpy) is:
public virtual string ToString()
{
return GetType().ToString();
}
This reads the type information and calls ToString on the type object itself, which simply returns the name of the type.
As others have answered, in order to get a listing of the items within the array, you need to invoke an enumerator of some sort. There are many different ways in C#, the best option depends on your end goal.
you miss iteration
for (int i = 0; i < bytes.Length; i++)
{
Console.WriteLine(bytes[i]);
}

Why do I get a "Cannot implicitly convert type 'char[]' to 'string' [C# programs]"

... when I try this in C#:
string reversedName;
reversedName = name.ToCharArray().Reverse().ToArray();
But not when I try this:
string reversedName = new string (name.ToCharArray().Reverse().ToArray());
? And when I try adding chaining a To.String() to the end of the first method, the Runtime doesn't throw an exception but returns: System.Char[]
I'm looking for an explanation on why the compiler seems to not be able to implicitly convert char[] to string:
* except when, apparently, calling new string,
* even when we chain the ToString() function to the end there.
When you try
string reversedName = new string (name.ToCharArray().Reverse().ToArray());
you are creating string with its constructor. As you can see, first parameter is array of chars:
https://msdn.microsoft.com/en-us/library/ms131424(v=vs.110).aspx
But here
reversedName = name.ToCharArray().Reverse().ToArray();
you are returning an array (with .ToArray() at the end), which is obviously not assignable to variable of type string.
Calling ToString() on array will print its type System.Char[], as you already noticed.
The ToString() on an Char Array object will return System.Char[] because it's the default and expected behavior. The compiler cannot assume that you want to join every char into one string, and return that string.
The correct way is to use new string(char[]).
You can also always use a Extension class to add a extension method.
public static class Extensions
{
public static string ConvertToString(this char[] array)
{
return new string(array);
}
}
Usage:
string s = array.ConvertToString();

C# Methods with infinite parameters array access

After learning how to Create a method with infinite parameters, I wonder is it legal to store the parameter array into a array. Will it cause any problem, since I don't see many people use this approach.
Code below :
class Foo
{
private String[] Strings;
public Foo(params String[] strings)
{
Strings = strings;
}
...
}
That's fine - it's just an array.
All the compiler does with a parameter array is convert a call like this:
Foo("x", "y");
into:
Foo(new string[] { "x", "y" });
That's really all there is to it. Anything you'd expect to be appropriate with the second call is fine with a parameter array.
Arrays passed into public methods are rarely suitable to store directly due to all arrays being mutable - but that's a matter of how you handle mutable parameter types rather than being specific to parameter arrays.

How to define type and value of variable in parameter of method in c#?

Is it possible to define type and value of variable in parameter of method (existing types string, int, double or your own types)?
Reason for that is to define variable only at parameter not out of function, like other variable.
Example just for test:
public string test(string x){ return x; }
test(new StringBuilder{"New created string!!!"}[0].ToString()));
above will just return first char, we want to return hole string (or any other type).
If we try to use test method we will use it like this:
1. example
string x = "some string";
test(x);
or
2. example
test("some string");
could we make something to write variable inside parameter of method, something like
3. example (not valid)
test(new string("some string "));
point is that you put variable without previously define it like in 1 or 2 example
Sure, you can pass a "new" value into a function - you don't have to declare it outside of the function call.
I think your confusion comes from your incorrect syntax for creating a new StringBuilder:
test(new StringBuilder("New created string!!!")[0].ToString()));
or
test(new StringBuilder[]{new StringBuilder("New created string!!!")}[0].ToString()));
if your intent was to create an array of StringBuilders and then pass in the first one.
You can also use the output of another function directly in the call:
test(MethodThatReturnsAString());
Otherwise I have no idea what you're trying to do...
The cause of the confusion seems to be that System.String doesn't have a constructor that takes a System.String. The following statement will not compile:
string x = new string("some string");
However, this will:
string x = "some string";
For all intents and purposes, the above two lines are the same.

Why we should use ToString method with StringBuilder?

MSDN says we need to convert StringBuilder object to string, but StringBuilder works fine?
Why should we convert?
string[] spellings = { "hi", "hiii", "hiae" };
StringBuilder Builder = new StringBuilder();
int counter = 1;
foreach (string value in spellings)
{
Builder.AppendFormat("({0}) Which is Right spelling? {1}", counter, value);
Builder.AppendLine();
counter++;
}
Console.WriteLine(Builder); // Works Perfectly
//Why should i use tostring like below
Console.WriteLine(Builder.ToString());
// Does it make any difference in above two ways.
Console.ReadLine();
These two calls use different Console.WriteLine overloads: WriteLine(Object) and WriteLine(String).
And the WriteLine(object) overload calls "... the ToString method of value is called to produce its string representation, and the resulting string is written to the standard output stream." (msdn)
Edit
The only difference here I can see is:
StringBuilder sb = null;
Console.WriteLine(sb); // prints terminator
Console.WriteLine(sb.ToString()); // throws NullReferenceException
In that specific example, both work fine, because Console.WriteLine will call the ToString() for you, on anything you pass it. The following also works:
Console.WriteLine(3); //called with an int;
Console.WriteLine(DateTime.Now);
Console.WriteLine(new {}); //called with an object
However, since the StringBuilder is not a string, (but an object that can make a string for you), you cannot pass it to a method that expects a string, i.e.
public void PrintMe(string value)
{
Console.WriteLine(value);
}
StringBuilder sb = new StringBuilder();
PrintMe(sb); // this will not work
Both lines of code to write to the console are doing the same thing in a different way. The second is more obvious though.
Console.WriteLine(Builder); uses the overloaded WriteLine() method that takes an object. As mentioned here the ToString() method will be called on the Builder:
'If value is null, only the line terminator is written. Otherwise, the
ToString method of value is called to produce its string
representation, and the resulting string is written to the standard
output stream.'
In the second line Console.WriteLine(Builder.ToString()); you are calling the ToString() method explicitly. This is preferable because it is immediately apparent to a developer what the code is doing.
this is from code-behind on a web form. i appended several times to my StringBuilder and accidentally did
return "[" + sbFinalContents + "]";
and i haven't had any trouble with it. i accidentally left off the ToString() part and i didn't even notice for a few days. any idea why this does not blow up?
StringBuilder.ToString Method (.net 4.) : "You must call the ToString method to convert the StringBuilder object to a String object before you can pass the string represented by the StringBuilder object to a method that has a String parameter or display it in the user interface."
technically, i'm not doing either one (i'm just returning a string), but i'm still surprised it hasn't failed.

Categories

Resources