C # Question about property inheritance

How do I inherit a property in C # from an interface and give that property a different name in the class?

For instance:

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 is also the same in the class. What I want is to give a different name to the property in the class, but still point 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

      

+2


a source to share


2 answers


If you inherit a property, you inherit from it, name, type and that's it. The name cannot be changed.

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

See what you can do on this page .



The only way to achieve what you want (have a property UserId

and an impelement IIdentity

) is to call IIdentity.Name

from it).

This will hide the property IIdentity.Name

from users of your class (unless they pounce on IIdentity

):

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

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

      set 
      { 
        IIdentity.Name = value;
      }
}

      

0


a source


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;}
}

      

+1


a source







All Articles