0

This is my code:

var myList = myPage.News.Cast<MyNew>();

MyNew have somethings like 20 property (Name, Title, Date, Place, etc etc) but it miss one, the property (for example) Tel.

Can't recreate my whole structure (it also become from a DLL), so I'd like to faster add a property of MyNew called Tel, inside that list. So extend the class during the insert in a list.

rptwsthi
  • 10,094
  • 10
  • 68
  • 109
markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 2
    You could add it as an extension method called `Tel()` to `MyNew` perhaps? No extension properties sadly. – Lloyd Mar 06 '13 at 14:44
  • 1
    Is the `MyNew` class sealed as if it is not you might be able to inherit from the class adding on any properties you need – Kane Mar 06 '13 at 14:44
  • Are you expecting that this property should be available on compile time so you can fere to it in a C# code or it participates in run time stuff only? – sll Mar 06 '13 at 14:44

3 Answers3

3

No, but you could create an anonymous type that includes the original type plus your new column:

var myList = myPage.News
                   .Cast<MyNew>()
                   .Select( new { m => MyNew = m,
                                       Tel = [formula for tel]
                                }
                          );
D Stanley
  • 149,601
  • 11
  • 178
  • 240
1
public class MyNewExtended: MyNew {
   public String Tel { get;set; }
}

var myList = myPage.News.Cast<MyNewExtended>();

(but see Chris Sinclair's comment below)

Jeffrey Knight
  • 5,888
  • 7
  • 39
  • 49
  • 2
    Assuming `News` is `IEnumerable`, the `Cast` will fail because they _aren't actually_ objects of the subclass type. – Chris Sinclair Mar 06 '13 at 14:47
  • I had no idea Cast() was so tricky ("the behaviour of Cast() was changed between .NET 3.5 and .NET 3.5 SP1") -- http://stackoverflow.com/questions/445471/puzzling-enumerable-cast-invalidcastexception – Jeffrey Knight Mar 06 '13 at 15:01
  • 1
    Just think of it like a literal type-cast to a _subclass_. It will _not_ perform any _conversion_ even if an explicit/implicit conversion exists. (but since `MyNewExtended` extends `MyNew` you wouldn't be able to write a user-defined conversion anyway) – Chris Sinclair Mar 06 '13 at 15:16
-1

You should be able to extend MyNew with a partial class like so:

public partial class MyNew
{
    public int Tel { get; set; }
}

Tel will then be available like any other property.

Vaze
  • 144
  • 7