How to define an alias for a property
Asked Answered
F

2

9

I want to generate aliases for properties in generated code. All I could do so far was:

partial class Purchase
{
    public User Customer
    {
        get
        {
            return this.User;
        }

        set
        {
            this.User = value;
        }
    }
}

I wonder if there is any other way to define an alias in C#. The Purchase class was generated by Linq-to-SQL

Fanciful answered 23/5, 2012 at 20:0 Comment(4)
Won't Linq2Sql let you alter mapped names?Amazonas
@HenkHolterman If I do that I would have to repeat the process every time I regenerate the DBML file.Fanciful
OK, if that is an issue. But your posted code is making an alias. So what the actual question? Is there anything wrong with it?Amazonas
@HenkHolterman nothing wrong. I just feel repeating myself when I have to say that Customer both gets and sets the same property and I know that are some obscure C# features and I wondered if any of them could make my code a little less verbose.Fanciful
C
1

No, it's not possible to do in C#. Property name is single identifier you can define for it.

Don't know if this is what you're searching for or not:

but you can define (say) a Dictionary<string,object> where Key is a propertyname and value is a value of the property. In this way you can define dynamic property cash, with changing property names and values at runtime.

or can use an ExpandoObject , if you use C# 4.0

Canossa answered 23/5, 2012 at 20:1 Comment(1)
In the posted code Customer is an alias for User. The OP asks for other ways to do it.Amazonas
L
7

In the case that you want a different name of property to send information to JSON using newtonSoft, you can use

 [JsonProperty("alias_name")]
 public type YourProperty {get;set;}

This can help you if you don't want that your object follow the C# convention and match with the JSON object to be received or sent

Luckin answered 12/4, 2017 at 20:18 Comment(1)
This is exactly what I was looking for. Thank you.Lassa
C
1

No, it's not possible to do in C#. Property name is single identifier you can define for it.

Don't know if this is what you're searching for or not:

but you can define (say) a Dictionary<string,object> where Key is a propertyname and value is a value of the property. In this way you can define dynamic property cash, with changing property names and values at runtime.

or can use an ExpandoObject , if you use C# 4.0

Canossa answered 23/5, 2012 at 20:1 Comment(1)
In the posted code Customer is an alias for User. The OP asks for other ways to do it.Amazonas

© 2022 - 2024 — McMap. All rights reserved.