In C# you cannot override the
It's polymorphism what I missed.ToString()
method of an IEnumerable
.
Therefore this
IEnumerable<char> chars = new List<char> { 'a', 'b', 'c' };
chars.ToString();
doesn't give me "abc".
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?
CodePudding user response:
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