Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set value of property in constructor (explicit interface implementation)

Tags:

c#

interface

[DataContract]
public class OrderSyncData : ISync
{

    public OrderSyncData(Order o)
    {
        this.CurrentOrderStatus = o.DriverStatus;
        this.StatusDescription = o.StatusDescription;
        SyncTimestamp = o.SyncTimestamp; ????
    }
    [DataMember]
    public string CurrentOrderStatus { get; set; }
    [DataMember]
    public string StatusDescription { get; set; }
    [DataMember]// I don't think I need these any more
    public bool IsCanceled { get; set; }
    [DataMember]
    public bool IsResolved { get; set; }
    [DataMember]
    public bool IsPendingResponse { get; set; }

    DateTime ISync.SyncTimestamp { get; set; }
}

How to set the value of ISync.SyncTimestamp? I tried casting the "this." but it doesn't work

like image 236
Ryan Avatar asked Feb 14 '13 19:02

Ryan


3 Answers

This should work:

((ISync)this).SyncTimestamp = o.SyncTimestamp;

Note the extra braces around (ISync)this.

like image 96
Daniel A.A. Pelsmaeker Avatar answered Nov 14 '22 19:11

Daniel A.A. Pelsmaeker


You just need to cast this:

((ISync) this).SyncTimestamp = o.SyncTimestamp;

Or you could do it in two statements:

ISync sync = this;
sync.SyncTimestamp = o.SyncTimestamp;

Basically, the explicit interface implementation means that the property is only available when you're viewing this in the context of simply ISync, not the implementation class.

like image 29
Jon Skeet Avatar answered Nov 14 '22 19:11

Jon Skeet


This is because you've implemented SyncTimestamp explicitly. Explicit implementations cannot be accessed from a class instance. Why? Because explicit implementation allows you to implement multiple interfaces with the same member name.

class Foo: IBar, IFoo
{
    bool IBar.FooBar {get;set;}
    bool IFoo.FooBar {get;set;}
}

Then writing this.FooBar refers to which implementation? So either you cast this to the desired interface explicitly, like other answers suggest, or you don't implement the SyncTimestamp explicitly, but do it implicitly: public DateTime SyncTimestamp { get; set; }. Then this.SyncTimestamp will work.

like image 28
Roman Royter Avatar answered Nov 14 '22 18:11

Roman Royter