Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# return concatenation of properties

Tags:

c#

I have a class:

public class LabOccurrenceForm
{          
    public DateTime Occurrence_Date { get; set; }
    public string Cup_Type { get; set; }
    public string Analytical_Testing_Phase { get; set; }
    public string Area { get; set; }
    public string Preanalytical_Before_Testing { get; set; }
    public string Postanalytical_After_Testing { get; set; }
    public string Other { get; set; }
    public string Practice_Code { get; set; }
    public string Comments { get; set; }
}

I would like to add a method in the class that will concatenate all the variables like this:

public string AllData
{
    return Occurrence_Date.ToString() + " " +
    Cup_Type + " " +
    Analytical_Testing_Phase + " " +
    Area + " " +
    Preanalytical_Before_Testing + " " +
    Postanalytical_After_Testing + " " +
    Other + " " +
    Practice_Code + " " +
    Comments;
}

This did not work because it wants a get or set. What am I doing wrong? How can I fix this?

like image 673
Alex Gordon Avatar asked Jul 15 '11 18:07

Alex Gordon


2 Answers

So, make it a property and give it a get...

public string AllData
{
    get
    {
        return Occurrence_Date.ToString() + " " +
        Cup_Type + " " +
        Analytical_Testing_Phase + " " +
        Area + " " +
        Preanalytical_Before_Testing + " " +
        Postanalytical_After_Testing + " " +
        Other + " " +
        Practice_Code + " " +
        Comments;
    }
}

Or make it a method...

public string AllData()
{
    return Occurrence_Date.ToString() + " " +
    Cup_Type + " " +
    Analytical_Testing_Phase + " " +
    Area + " " +
    Preanalytical_Before_Testing + " " +
    Postanalytical_After_Testing + " " +
    Other + " " +
    Practice_Code + " " +
    Comments;
}

Or override ToString() instead (which sort of makes sense in this context)

public override string ToString()
{
    return Occurrence_Date.ToString() + " " +
    Cup_Type + " " +
    Analytical_Testing_Phase + " " +
    Area + " " +
    Preanalytical_Before_Testing + " " +
    Postanalytical_After_Testing + " " +
    Other + " " +
    Practice_Code + " " +
    Comments;
}
like image 101
canon Avatar answered Oct 25 '22 22:10

canon


Since you want all properties - more succinct using reflection:

public string GetAllData()
{
    return string.Join(" ", typeof(LabOccurrenceForm).GetProperties().Select(x => x.GetValue(this, null)));
}
like image 25
BrokenGlass Avatar answered Oct 25 '22 21:10

BrokenGlass