user3393933
user3393933

Reputation:

how to set private structure fields in a public property?

I have a structure:

public struct ServiceDescription
        {
            string serviceDescriptionText;
            string serviceLogoRef;

            /// <summary>
            /// The position to print the service on the label.
            /// </summary>
            int servicePosition;

            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="serviceDescriptionText"></param>
            /// <param name="serviceLogoRef"></param>
            /// <param name="servicePosition"></param>
            public ServiceDescription(string serviceDescriptionText, string serviceLogoRef,
                                        int servicePosition)
            {
                this.serviceDescriptionText = serviceDescriptionText;
                this.serviceLogoRef = serviceLogoRef;
                this.servicePosition = servicePosition;
            }
        }

and a property:

public string pServiceDescription
{
    get
    {
        return p_sServiceDescription;
    }
    // set private structure field 1
    // set private structure field 2
    // etc...
}

How do I set each of the private fields of the structure in the setters of my property?

Upvotes: 0

Views: 2144

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063338

It is usually a very bad idea to have mutable structs; mutable value-type semantics is not what people usually expect. You can, however, simply add a set that works like any other regular setter. It just isn't a very good idea:

public string Text
{
    get { return text; }
    set { text = value; } // this is a really bad idea on a struct
}

If it was me, that would be an immutable struct with private readonly fields and a constructor that sets all of them (and get-only properties), or a class - probably with automatically implemented properties, i.e.

public class ServiceDescription {
    public string Text {get;set;}
    //...
}

Upvotes: 4

Related Questions