Implements IFormattable with switch statement
using System;
public class Employee : IFormattable {
private string title;
private string[] names;
public Employee(string title, params string[] names) {
this.title = title;
this.names = names;
}
public override string ToString() {
return ToString("G", null);
}
public string ToString(string format, IFormatProvider formatProvider) {
string result = null;
if (format == null) format = "G";
switch (format.ToUpper()[0]) {
case 'S':
result = names[0][0] + "." + names[names.Length - 1];
break;
case 'P':
if (title != null && title.Length != 0) {
result = title + ".";
}
break;
case 'I':
result = names[0];
break;
case 'G':
default:
result = names[0] + " " + names[names.Length - 1];
break;
}
return result;
}
}
public class MainClass {
public static void Main() {
Employee person = new Employee("Mr", "A", "B", "C", "D");
System.Console.WriteLine("{0:G},", person);
System.Console.WriteLine("{0:P},", person);
System.Console.WriteLine("{0:I},", person);
System.Console.WriteLine("{0},", person);
System.Console.WriteLine("{0:S},", person);
}
}
|
HTML code for linking to this page:
Related in same category :
-
-
|
|