Path.Combine - C# 3.0 Extension Method

O data cu C# 3.0 au venit si metodele extensie. Sunt foarte utile cand se vrea a se extinde o clasa care nu poate fi mostenita cum e clasa string.

Un alt avantaj e ca schimba notatia prefix a metodelor statice cu una infix, ceea ce face codul mult mai clar si mai usor de scris.

De exemplu metoda statica Combine din clasa Path concateneaza doua stringuri pentru a obtine o cale fizica valida. Pentru doua stringuri e OK, dar atunci cand se combina mai mult de doua stringuri deja incepi sa numeri paranteze.



public static class PathExtension
{
public static string Combine(this string instance, string path2)
{
return Path.Combine(instance, path2);
}
}
class Program
{
static void Main(string[] args)
{
string root = "C:\\";
string mainFolder = "Files";
string subFolder = "Backup";
string fileName = "today.xml";

// notatie prefix
Console.WriteLine(
Path.Combine(
Path.Combine(
Path.Combine(root, mainFolder),subFolder),fileName));

// notatie infix
Console.WriteLine
(
root.Combine(mainFolder)
.Combine(subFolder)
.Combine(fileName)
);

}
}

Comments

Popular posts from this blog

IIS 7.5, HTTPS Bindings and ERR_CONNECTION_RESET

Verify ILogger calls with Moq.ILogger

Table Per Hierarchy Inheritance with Column Discriminator and Associations used in Derived Entity Types