Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does IEnumerable<char> ToString() work in xamarin android?

In C# you cannot override the ToString() method of an IEnumerable.
It’s polymorphism what I missed.

Therefore this

IEnumerable<char> chars = new List<char> { 'a', 'b', 'c' };
chars.ToString();

doesn’t give me "abc".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Looking into some Xamarin.Android I wonder how the following converts into the correct string:

//In OnCreate
FindViewById<EditText>(Resource.Id.txt_username).TextChanged += GenerateNewPassword;


//my method
private void GenerateNewPassword(object sender, Android.Text.TextChangedEventArgs e)
{
    passwordView.Text = e.Text.ToString();
}

What am I missing, why does this work?

>Solution :

The ToString override is coming from the underlying type, not the IEnumerable<T>. I’m not sure how Xamarin is providing that exactly, but I presume it is a custom type that implements IEnumerable<T>. For example, we can do this:

public class MyList<T> : List<T>
{
    public override string ToString()
    {
        return string.Join("", this);
    }
}

And now we can do this:

IEnumerable<char> chars = new MyList<char> { 'a', 'b', 'c' };
Console.WriteLine(chars.ToString());

Which will output:

abc

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading