Tony_Henrich
Tony_Henrich

Reputation: 44085

Can a property in a class have a second name or an alias in .NET?

Is there a way in .NET to have a class property have a second name or an alias. I want the alias to show in Visual Studio Intellisense? The reason is for me to know what property maps to what column in a database and if I put the column name somewhere with the corresponding property, I can easily know how the mappings work.

Upvotes: 0

Views: 166

Answers (4)

JaredPar
JaredPar

Reputation: 754763

There is no way to do this at a metadata or even a language level. However you can use simple properties that forward their requests to achieve the same result

public class Student {
  private  string _name;
  public string ColumnName { get { return _name; } set { _name = value; } }
  public string Name { get { return ColumnName; } set { ColumnName = value; }}
}

Upvotes: 1

Sani Huttunen
Sani Huttunen

Reputation: 24385

You could simply add another property assigning the one you want an "alias" for.

public String InnerProp { get; set; }
public String AliasProp
{
  get { return this.InnerProp; }
  set { this.InnerProp = value; }
}

Upvotes: 1

Adam Ralph
Adam Ralph

Reputation: 29956

You could put the column name in an XML comment on the property, e.g.

/// <summary>
/// Maps to column 'foo'
/// </summary>
public int Foo { get; set; }

The content of the XML comment will show in the intellisense tooltip for the Foo property.

Upvotes: 8

heavyd
heavyd

Reputation: 17721

I don't think there is anyway to give it an alias, but you could easily create another property with a different name that just accesses the property you are trying to get to.

class MyClass
{
  private int myVal;

  public int MyProperty
  {
    get { return this.myVal; }
    set { this.myVal = value; }
  }

  public int MyDbProperty
  {
    get { return this.MyProperty; }
    set { this.MyProperty = value; }
  }
}

Upvotes: 5

Related Questions