RobVious
RobVious

Reputation: 12915

How to map one property to another using C#?

I have a User Class:

public class User {
    public int UserId {get; set;}
    public string Username {get; set;}
    }

I'm trying to add an Email property that gets and sets the Username property - they're the same thing, but I don't need to add another physical property to the model, just a reference.

I know this means I have to use a custom get and set, but I'm stuck with the syntax. Those terms are so ambiguous so I haven't had much luck pulling anything relevant up. Any help would be much appreciated!

Upvotes: 0

Views: 80

Answers (4)

Stijn Hoste
Stijn Hoste

Reputation: 874

Public Class User
{
   private string username;
   private string email;

   public string GetUsername()
   {
       return this.username;
   }

   public void SetUsername(string parUsername)
   {
       return this.username = parUsername;
   }

}

Upvotes: -1

p.s.w.g
p.s.w.g

Reputation: 149020

It should look a bit like this:

public class User 
{
    public int UserId { get; set; }
    public string Username { get; set; }
    public string Email 
    {
        get { return this.Username; }
        set { this.Username = value; }
    }
}

Upvotes: 2

rerun
rerun

Reputation: 25505

public class User {
    public int UserId {get; set;}
    public string Username {get; set;}
    public string Email{
        get
        {
            return UserId;
        }
        set 
        {
            UserId = value;
        }
    }

Upvotes: 1

Marvin Smit
Marvin Smit

Reputation: 4108

SOmething like this you mean?

public string Email 
{
   get
   {
      return this.Usename;
   }
   set
   {
      this.Username = value;
   }
}

Upvotes: 5

Related Questions