Coffeehouse Thread

42 posts

C# Extension Properties?

Back to Forum: Coffeehouse
  • User profile image
    frindly1000

    Dr Herbie said:
    dahat said:
    *snip*
    Well, without the extension method language feature, you'd have to use the decorator pattern. If you only want to add a single method, that's potentially an awful lot of work, which is why I like extensions.

    For me the real strength of extension methods is in adding type-inferenced extension methods to interface, so that classes inheriting that interface automatically get interface-related functionality for free (we discussed this a while ago over on this thread).


    Herbie


    In regards to extension methods being confusing, I agree in that extension methods are extraordinarily powerful and thus have dramatic potential for misuse.  However there are a few cases such as adding context specific methods to base objects like object or string or adding methods to a system interface like IList where they are the best way to perform the move.

     

    That being said it is sad that extension properties, which seem to me to be no more or less powerful or appropriate than extension methods were not included simply because an agreement on the declaration syntax could not be reached.

  • User profile image
    joechung

    Dr Herbie said:
    dahat said:
    *snip*
    Well, without the extension method language feature, you'd have to use the decorator pattern. If you only want to add a single method, that's potentially an awful lot of work, which is why I like extensions.

    For me the real strength of extension methods is in adding type-inferenced extension methods to interface, so that classes inheriting that interface automatically get interface-related functionality for free (we discussed this a while ago over on this thread).


    Herbie


    You cannot subclass a sealed class or a struct to implement the decorator pattern.

    EDIT: Oops, thread necromancy.  grr, frindly1000!

  • User profile image
    exoteric

    frindly1000 said:
    Dr Herbie said:
    *snip*

    In regards to extension methods being confusing, I agree in that extension methods are extraordinarily powerful and thus have dramatic potential for misuse.  However there are a few cases such as adding context specific methods to base objects like object or string or adding methods to a system interface like IList where they are the best way to perform the move.

     

    That being said it is sad that extension properties, which seem to me to be no more or less powerful or appropriate than extension methods were not included simply because an agreement on the declaration syntax could not be reached.

    Still, using a pair of empty ellipses, you can still achieve the same effect, i.e. (for gets, not for sets)

     

    20.Minutes().Ago()

     

    I believe in Scala you can use any method using infix notation so you might be able to express something like

     

    20 minutes ago

     

    I'm experimenting with using extension methods to achieve null-safe "object-oriented" expressions

     

    int? v = element.Value().Eval<int>();

     

    Value(), as an extension method over XElement, and Eval as an extension method over object, are both null-safe. If element is null, then the whole expression evaluates to null; if element.Value() is null, then the whole expression evaluates to null; if element.Value().Eval<int>() is not possible (format error or unsupported conversion), then the whole expression evaluates to null. 

     

    This property, that one can model null-safety with extension methods is absolutely adorable.

     

    I think the C# field/method/property system is a bit non-uniform now, but it's still very useable and powerful.

  • User profile image
    mrjvdveen

    exoteric said:
    frindly1000 said:
    *snip*

    Still, using a pair of empty ellipses, you can still achieve the same effect, i.e. (for gets, not for sets)

     

    20.Minutes().Ago()

     

    I believe in Scala you can use any method using infix notation so you might be able to express something like

     

    20 minutes ago

     

    I'm experimenting with using extension methods to achieve null-safe "object-oriented" expressions

     

    int? v = element.Value().Eval<int>();

     

    Value(), as an extension method over XElement, and Eval as an extension method over object, are both null-safe. If element is null, then the whole expression evaluates to null; if element.Value() is null, then the whole expression evaluates to null; if element.Value().Eval<int>() is not possible (format error or unsupported conversion), then the whole expression evaluates to null. 

     

    This property, that one can model null-safety with extension methods is absolutely adorable.

     

    I think the C# field/method/property system is a bit non-uniform now, but it's still very useable and powerful.

    True, but you can't use that in something like databinding (in WPF or Silverlight at least). Sometimes you just need a property.

    Having extension properties would be extremely powerful in a scenario where you use something like LinqToSql in a service, use partial classes there to make properties available in the DataContract and then use some extension properties to format some properties for databinding.

    I know I could do the latter with a valueconverter but I find that more troublesome then it needs to be.

  • User profile image
    contextfree

    Coding WPF classes in C# sometimes feels like coding COM classes in C++: you have to explicitly provide plumbing that obscures the high-level abstractions.  XAML is nicer, but it's both limited in capability and saddled with clunky XML syntax.  This is my biggest problem with WPF, an API that in the abstract is very nice, I just wish there were a better view into it ... like JavaFX Script.   Tongue Out

  • User profile image
    Maddus Mattus

    contextfree said:

    Coding WPF classes in C# sometimes feels like coding COM classes in C++: you have to explicitly provide plumbing that obscures the high-level abstractions.  XAML is nicer, but it's both limited in capability and saddled with clunky XML syntax.  This is my biggest problem with WPF, an API that in the abstract is very nice, I just wish there were a better view into it ... like JavaFX Script.   Tongue Out

    Blend doesnt suit your needs?

  • User profile image
    contextfree

    Maddus Mattus said:
    contextfree said:
    *snip*

    Blend doesnt suit your needs?

    I haven't used it much, but it's a visual designer, right?  There's more to WPF than visual design.  I'm thinking of setting up dependency properties, etc.

  • User profile image
    Jonwib

    mabster said:
    Yeah, I was hoping for extension properties too:

    public static TimeSpan Minutes[this int i]
    {
       getreturn new TimeSpan(0, i, 0); }
    }

    public static DateTime Ago[this TimeSpan ts]
    {
       get { return DateTime.Now.Subtract(ts); }
    }


    So then I could do:

    DateTime d = 20.Minutes.Ago;

    No ugly parentheses!

    Or you could use VB.NET, where you don't need parentesis after methods Wink

    Me to would like extension properties in .net c#; more lika an Aspect oriented aproach

  • User profile image
    Exception​Duck

    Jonwib said:
    mabster said:
    *snip*

    Or you could use VB.NET, where you don't need parentesis after methods Wink

    Me to would like extension properties in .net c#; more lika an Aspect oriented aproach

    I did something like this to copy Jquery.data function

     

    public static class extends{
      public static Dictionary> v = new Dictionary>();
      public static object data(this object o, object key,object val = null)
      {
       if (!v.ContainsKey(o))
       v[o] = new Dictionary();
       if(val!=null)
        return v[o][key];
       v[o][key] = val;
       return val;
      }
    }


    It won't distinguish between equal simple types, but for complex it works well.

     

    With this you can call any object's data method

     

    F = new Form();

    F.data("language","EN");

     

    and inside F you could call

     

    this.data("language") and it would return "EN"

  • User profile image
    Massif

    ExceptionDuck said:
    Jonwib said:
    *snip*

    I did something like this to copy Jquery.data function

     

    public static class extends{
      public static Dictionary> v = new Dictionary>();
      public static object data(this object o, object key,object val = null)
      {
       if (!v.ContainsKey(o))
       v[o] = new Dictionary();
       if(val!=null)
        return v[o][key];
       v[o][key] = val;
       return val;
      }
    }


    It won't distinguish between equal simple types, but for complex it works well.

     

    With this you can call any object's data method

     

    F = new Form();

    F.data("language","EN");

     

    and inside F you could call

     

    this.data("language") and it would return "EN"

    Wow, thread Necromancy!

     

    Also, use F# you can extend everything Smiley

  • User profile image
    koistya

    Property extensions in C# 5.0

    // A product type in this sample has a property Name of type String
    var product = new Product();
    
    // This will print "Product.Name.IsDirty: False"
    Console.WriteLine("Product.Name.IsDurty: {0}", product.Name.IsDirty);
    
    // Now let's try to update product's Name property
    product.Name = "C# 4.0 in a Nutshell";
    
    // And now this will print "Product.Name.IsDirty: True"
    Console.WriteLine("Product.Name.IsDurty: {0}", product.Name.IsDirty);
    
    // Then when you try to save this product in database, it will be easier for
    // Store Repository detect which fields must be saved and which can be skipped
    storeRepository.Add(product);
    storeRepository.SubmitChanges();

  • User profile image
    W3bbo

    koistya said:

    Property extensions in C# 5.0

    // A product type in this sample has a property Name of type String
    var product = new Product();
    
    // This will print "Product.Name.IsDirty: False"
    Console.WriteLine("Product.Name.IsDurty: {0}", product.Name.IsDirty);
    
    // Now let's try to update product's Name property
    product.Name = "C# 4.0 in a Nutshell";
    
    // And now this will print "Product.Name.IsDirty: True"
    Console.WriteLine("Product.Name.IsDurty: {0}", product.Name.IsDirty);
    
    // Then when you try to save this product in database, it will be easier for
    // Store Repository detect which fields must be saved and which can be skipped
    storeRepository.Add(product);
    storeRepository.SubmitChanges();

    That's not the same thing, that's "properties for properties" which is just messed up in my opinion.

     

    I'm perfectly happy with C# 2.0, I only rarely use C# 3.0 (and when I do, it's for Linq).

     

    Wait a sec... this isn't an official blog posting, you're not an employee or someone involved in the language design process. Is this just an example you're proposing or what?

  • User profile image
    koistya

    W3bbo said:
    koistya said:
    *snip*

    That's not the same thing, that's "properties for properties" which is just messed up in my opinion.

     

    I'm perfectly happy with C# 2.0, I only rarely use C# 3.0 (and when I do, it's for Linq).

     

    Wait a sec... this isn't an official blog posting, you're not an employee or someone involved in the language design process. Is this just an example you're proposing or what?

    W3bbo, I am trying to make people think and be creative imagining the feature with me Wink

  • User profile image
    cheong

    koistya said:

    Property extensions in C# 5.0

    // A product type in this sample has a property Name of type String
    var product = new Product();
    
    // This will print "Product.Name.IsDirty: False"
    Console.WriteLine("Product.Name.IsDurty: {0}", product.Name.IsDirty);
    
    // Now let's try to update product's Name property
    product.Name = "C# 4.0 in a Nutshell";
    
    // And now this will print "Product.Name.IsDirty: True"
    Console.WriteLine("Product.Name.IsDurty: {0}", product.Name.IsDirty);
    
    // Then when you try to save this product in database, it will be easier for
    // Store Repository detect which fields must be saved and which can be skipped
    storeRepository.Add(product);
    storeRepository.SubmitChanges();

    > product.Name = "T-Short";
    > product.Name.IsDirty

    Actually there's nothing prevent you to use "product.Name_IsDirty". That kind of extension makes so little in readability improvement so probably just not worth the effort to change.

    Recent Achievement unlocked: Code Avenger Tier 4/6: You see dead program. A lot!
    Last modified
  • User profile image
    W3bbo

    cheong said:
    koistya said:
    *snip*

    > product.Name = "T-Short";
    > product.Name.IsDirty

    Actually there's nothing prevent you to use "product.Name_IsDirty". That kind of extension makes so little in readability improvement so probably just not worth the effort to change.

    I can see a potential application with templates:

     

    struct DataProperty<T TData> {

     

    private TData _value;

    public event EventHandler PropertyChanged;

    public TData Value { get { return _value; } set { _value = value; PropertyChanged(this, EventArgs.Empty); IsDirty = true; }

    public bool IsDirty { get; private set; }

     

    }

     

    class SomeBusinessObject {

     

    public DataProperty<String> Name { get; private set; }

     

    }

     

    What do you guys think?

  • User profile image
    Sven Groot

    W3bbo said:
    cheong said:
    *snip*

    I can see a potential application with templates:

     

    struct DataProperty<T TData> {

     

    private TData _value;

    public event EventHandler PropertyChanged;

    public TData Value { get { return _value; } set { _value = value; PropertyChanged(this, EventArgs.Empty); IsDirty = true; }

    public bool IsDirty { get; private set; }

     

    }

     

    class SomeBusinessObject {

     

    public DataProperty<String> Name { get; private set; }

     

    }

     

    What do you guys think?

    1. Doesn't compile
    2. Doesn't work because it's a struct (foo.Name.Value = "whatever" would not change the value of Name but that of a temporary copy).
    3. Crashes if PropertyChanged is null.

  • User profile image
    Minh

    koistya said:

    Property extensions in C# 5.0

    // A product type in this sample has a property Name of type String
    var product = new Product();
    
    // This will print "Product.Name.IsDirty: False"
    Console.WriteLine("Product.Name.IsDurty: {0}", product.Name.IsDirty);
    
    // Now let's try to update product's Name property
    product.Name = "C# 4.0 in a Nutshell";
    
    // And now this will print "Product.Name.IsDirty: True"
    Console.WriteLine("Product.Name.IsDurty: {0}", product.Name.IsDirty);
    
    // Then when you try to save this product in database, it will be easier for
    // Store Repository detect which fields must be saved and which can be skipped
    storeRepository.Add(product);
    storeRepository.SubmitChanges();

    what is a "t-short" ?

     

    and yes, it does sound dirty

  • User profile image
    TommyCarlier

    Minh said:
    koistya said:
    *snip*

    what is a "t-short" ?

     

    and yes, it does sound dirty

    T-short

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.