C # how to use get; to return a value if the value has not been set?

I am trying to determine a value get; set;when initializing an attribute.

I have the following interface

public interface IReportColumn
{
    string Title { get; set; }

    string ColumnKey { get; }

    AggregateFunctions AggregateFunction { get; set; }

    string SqlAlias { get;  }

}

I need to make the attribute a SqlAliasrandom string if AggregateFunction == AggregateFunctions.None || ColumnKey == null. But, since I am generating a random string here, I do not want it to change when I call the get method. I want to get it, set and reuse the same value throughout the request.

This is how I implement my interface

public class ReportColumnMsSqlServer : IReportColumn
{

    public string Title { get; set; }

    public string ColumnKey { get; set; }

    public AggregateFunctions AggregateFunction { get; set; }

    public string SqlAlias {

        get {

           return this.GetColumnName();

        } 
    }


    private string GetColumnName()
    {
        string columName = this.ColumnKey;

        if (columName == null || this.AggregateFunction != AggregateFunctions.None)
        {
            columName = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
        }

        return string.Format("{0}", new Regex("[^a-zA-Z0-9]").Replace(columName, string.Empty));
    }

}

How to set the SqlAlias ​​value only once depending on my condition above and keep the same value throughout the query?

+4
source share
2 answers

:

private string _sqlAlias = null;
public string SqlAlias {

    get {
       if (_sqlAlias == null)
           _sqlAlias = this.GetColumnName();
       return _sqlAlias;

    } 
}

, ColumnKey, AggregateFunction, , _sqlAlias null, SqlAlias .

+5

" ".

private string _sqlAlias;
public string SqlAlias {
     get {
         if (_sqlAlias == null) {
             _sqlAlias = GetColumnName();
         }

         return _sqlAlias;
     }
}
+1

All Articles