Feedback

C# - Emulating F#''s ''with'' Construct in C# using Parameter Object

Veröffentlicht von am 12/13/2009
(2 Bewertungen)
This snippet introduces a way to emulate F#'s 'with' construct in C#. In particular, it shows how a factory method can be implemented which creates a new object based on a provided template object and optional additional values (replacing values of the template object) in a type-safe way. The following code shows an example using the proposed pattern:


var a1 = factory.CreateAttribute(
null,
new AttributeArgs {
StereoType = "author-info",
Name = "full-name",
Value = "Johann Duscher"
});

var a2 = factory.CreateAttribute(
a1,
new AttributeArgs {
Value = "Jonny Dee"}
});


While the presented solution doesn't use new C# 4.0 language features, using them for this task is also considered and discussed here: http://wp.me/pcfBw-6
public interface IAttribute
{
   string StereoType { get; set; }
   string Name { get; set; }
   string Value { get; set; }
}

public class AttributeArgs : IAttribute
{
   private string _stereoType;
   private string _name;
   private string _value;

   public string StereoType
   {
      get { return _stereoType; }
      set { _stereoType = value; StereoTypeSpecified = true; }
   }

   public bool StereoTypeSpecified { get; private set; }

   public string Name
   {
      get { return _name; }
      set { _name = value; NameSpecified = true; }
   }

   public bool NameSpecified { get; private set; }

   public string Value
   {
      get { return _value; }
      set { _value = value; ValueSpecified = true; }
   }

   public bool ValueSpecified { get; private set; }
}

public class Factory
{
   public IAttribute CreateAttribute(IAttribute template,
                                     AttributeArgs args)
   {
      if (null != template)
      {
         if (!args.StereoTypeSpecified)
            args.StereoType = template.StereoType;
         if (!args.NameSpecified)
            args.Name = template.Name;
         if (!args.ValueSpecified)
            args.Value = template.Value;
      }
      return new AttributeArgs {StereoType = args.StereoType,
                                Name = args.Name,
                                Value = args.Value,};
   }
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!