tags:

views:

83

answers:

2

Hi all,

How do i inherit a property in c# from an interface and give that property other name on the class?

For example:

public interface IFoo
{
  int Num {get;set;}
}

public class IFooCls : IFoo
{
  int Ifoo.Num{get;set}
}

In this case, what the property name in the interface is also the same in the class. What i want is to give other property name on the class but still pointing to "Num" in the interface in this case. In VB, we can do it like this:

Public ReadOnly Property UserId() As String Implements System.Security.Principal.IIdentity.Name
    Get
        Return _userId
    End Get
End Property
A: 

If you inherit a property, you inherit it, name, type and all. There is no way to change the name.

If you want, you can write another property with a different name and call the inherited property from it (you still have to implement the original property).

See what you can do on this MSDN page.

The only way to achieve what you want (have a UserId property and impelement IIdentity) is to call IIdentity.Name from it).

This will hide the IIdentity.Name property from users of your class (unless they cast to IIdentity):

public class myIdentity : IIdentity
{
   public string IIdentity.Name {get; set;}

   public string UserId 
   { 
      get 
      { 
        return IIdentity.Name;
      }

      set 
      { 
        IIdentity.Name = value;
      }
}
Oded
this is what we were currently doing.
mcxiand
@mcxiand - That's the only way you could, in C#. The only other "solution" would be to implement it in a VB.NET project and reference that project in your C# projects ;)
Oded
+1  A: 

Here is a way to simulate what you are trying to do in C#

public interface Foo {
  string Name {get;set;}
}

pubilc class Bar : Foo {

#region Foo implementation
  public string Name {get{return UserName;} set{UserName = value;}}
#endregion //Foo implementation

  public string UserName {get; set;}
}
Igor Zevaka
You can use explicit implementation of the interface to "hide" the `Name` member from users of the `Bar` class. I believe this is how VB.NET does it's thing under-the-hood.
Dean Harding