0

How would I go about aliasing a variable from it's plural form so that referencing the plural form changes or returns the single form?

I have a global variable as such with a Getter and Setter:

public string UserName { get; set; }

And would like to set up an aliased variable UserNames that would return UserName and when set would modify UserName?

I've tried public string UserNames { get => UserName; set => UserName = UserNames } but that didn't seem to work.

Delrog
  • 735
  • 2
  • 11
  • 27
  • 2
    Your setter would need to be `UserName = value` – Matt Burland Jun 05 '17 at 18:24
  • This isn't "aliasing"; there's a [C# feature called aliasing](https://msdn.microsoft.com/en-us/library/aa664765(v=vs.71).aspx) already. This is just forwarding. `a.get` returns `b`. – 15ee8f99-57ff-4f92-890c-b56153 Jun 05 '17 at 18:26
  • No array involved here, just trying to get the variable name UserName(s) to reflect the variable with name UserName. – Delrog Jun 05 '17 at 18:46
  • You are converting an array to a single string. So you would need to use something like CSV (seperated by commas). So try this : public string[] UserNames { get { return UserName.Split(new char[] {','});} set { UserName = string.Join(",",value);}} – jdweng Jun 05 '17 at 18:48

3 Answers3

5

Almost, you have to use value in your setter.

public string UserNames { get => UserName; set => UserName = value; } 
Igor
  • 60,821
  • 10
  • 100
  • 175
  • 1
    Note that this syntax requires C# 7 to be available – BradleyDotNET Jun 05 '17 at 18:28
  • @BradleyDotNET - true; the attempt in the OP is posted using c# 7 syntax so I figured an answer in c# 7 syntax was warranted. – Igor Jun 05 '17 at 18:29
  • So i tried this but initially but I get a build error? There is no code highlighting to signify where the error is coming from or anything in the errors tab. I then commented UserNames out and it built ( but without the 'aliased' functionality that I'm looking for ) – Delrog Jun 05 '17 at 18:33
  • @Delrog - You have to set your project properties to be built using c# 7. See this previous answer for where to set that in your project properties https://stackoverflow.com/a/43682193/1260204 – Igor Jun 05 '17 at 18:34
4

C# <7.0

public string UserNames { get { return UserName; } set { UserName = value; }}

C# 7.0

public string UserNames { get => UserName; set => UserName = value; }
adjan
  • 13,371
  • 2
  • 31
  • 48
1

You can write like this:

private string UserName;
public string UserNames
{
  get
  {
    return UserName;
  }  
  set
  {
    UserName=value;
  }
 }  
amin
  • 561
  • 6
  • 18